[英]Why is strtok printing only first word?
我正在使用strtok将字符串转换为单个单词 。 我做了以下事情:
int main() {
char target[100];
char *t;
scanf("%s",target);
t = strtok(target," ");
while (t!= NULL)
{
printf("<<%s>>\n", t);
t = strtok (NULL, " ");
}
return 0;
}
输入是一个字符串,例如'this is a string',我得到的输出是<<this>>
。
你写scanf
的方式只接受字符串直到空格
的scanf( “%S”,目标);
所以你需要改变从控制台获取输入的方式
scanf("%99[^\n]",target);
更改:
scanf("%s",target);
至:
fgets(target, 100, stdin);
因为第一个在遇到输入中的空格时不会停止。
输出:
this is a string
<<this>>
<<is>>
<<a>>
<<string
>>
注意换行符fgets()存储如何影响输出。 如果你愿意,你可以简单地丢弃它,如下所示:
fgets(target, 100, stdin);
target[strlen(target) - 1] = '\0';
现在的输出是:
this is a string
<<this>>
<<is>>
<<a>>
<<string>>
如果你想继续使用scanf() ,那么你可以使用下面的代码片段:
#include<stdio.h>
#include <string.h>
int main() {
char target[100];
char *t;
//scanf("%s",target);
scanf("%99[0-9a-zA-Z ]", target);
printf("%s\n",target);
t = strtok(target," ");
while (t!= NULL)
{
printf("<<%s>>\n", t);
t = strtok (NULL, " ");
}
return 0;
}
在这里工作代码。
只需编写scanf("%s",target);
将只读取输入直到第一个空格; 这就是为什么你只得到第一个单词作为输出。 通过写scanf("%99[0-9a-zA-Z ]", target);
,您正在从输入流中读取99个字符(包括数字0-9
, az
或AZ
和空格)。
希望这是有帮助的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.