使用换行符和空格读取字符串
reading string with newlines and spaces
我正在尝试从 stdin 解析一个字符串,例如这个 { 7 , 3,5 ,11, 8, 16, 4, 9, 2
,8, 4, 2}
(2 到 8 之间有一个 \n)。
我已经创建了一个函数来提取数字和 trim 逗号空格和换行符(接受 char* 作为输入)但是问题是当我尝试使用 scanf 获取输入时我无法获取空格所以我改用 fgets 但 fgets 会在看到 \n 时立即退出。
有没有办法从中获取字符串?
int nums[1000], count = 0;
char chr;
while(scanf("%c%d", &chr, &nums[count]) > 0) //there was at least one match
{
if(chr == '}')
break; //we have reached the end
if(chr != ',' && chr != '{')
continue; //skip spaces (} is an exception)
count++;
}
您可以使用 fgets
阅读整行并使用 strtok
阅读数字。下面的示例还将 \n
视为逗号 ,
char line[512];
char *buf = 0;
while(fgets(line, sizeof(line), stdin))
{
if(!strstr(line, "{") && !buf)
continue;
if(!buf)
{
buf = strdup(line);
}
else
{
buf = realloc(buf, strlen(buf) + strlen(line) + 1);
strcat(buf, line);
}
if(strstr(line, "}"))
{
char *token = strtok(buf, "{");
strtok(buf, ",}\n");
while(token)
{
int n = 0;
sscanf(token, "%d", &n);
printf("%d, ", n);
token = strtok(NULL, ",}\n");
}
free(buf);
break;
}
}
我正在尝试从 stdin 解析一个字符串,例如这个 { 7 , 3,5 ,11, 8, 16, 4, 9, 2
,8, 4, 2}
(2 到 8 之间有一个 \n)。
我已经创建了一个函数来提取数字和 trim 逗号空格和换行符(接受 char* 作为输入)但是问题是当我尝试使用 scanf 获取输入时我无法获取空格所以我改用 fgets 但 fgets 会在看到 \n 时立即退出。
有没有办法从中获取字符串?
int nums[1000], count = 0;
char chr;
while(scanf("%c%d", &chr, &nums[count]) > 0) //there was at least one match
{
if(chr == '}')
break; //we have reached the end
if(chr != ',' && chr != '{')
continue; //skip spaces (} is an exception)
count++;
}
您可以使用 fgets
阅读整行并使用 strtok
阅读数字。下面的示例还将 \n
视为逗号 ,
char line[512];
char *buf = 0;
while(fgets(line, sizeof(line), stdin))
{
if(!strstr(line, "{") && !buf)
continue;
if(!buf)
{
buf = strdup(line);
}
else
{
buf = realloc(buf, strlen(buf) + strlen(line) + 1);
strcat(buf, line);
}
if(strstr(line, "}"))
{
char *token = strtok(buf, "{");
strtok(buf, ",}\n");
while(token)
{
int n = 0;
sscanf(token, "%d", &n);
printf("%d, ", n);
token = strtok(NULL, ",}\n");
}
free(buf);
break;
}
}