我正在开发一个程序,将字符串中的单词分开,然后在不同的行上打印每个单词。我在输出时遇到了一些困难。对于前。
"This is a string"
打印
""this
"is"
"a"
"string"
"
代替
"this"
"is"
"a"
"string"
代码:
#include <string.h>
#include <stdio.h>
void wholestring(char S[]) {
int i;
for (i=0; i<strlen(S); ++i) {
}
return;
}
int main(){
const int mysize = 100;
char mystr[mysize];
char *newstr;
fgets(mystr, mysize, stdin);
wholestring(mystr);
newstr = strtok (mystr, " ");
while (newstr != '\0'){
printf ("\"%s\" \n", newstr);
newstr = strtok ('\0', " ");
}
return 0;
}
最佳答案
我在你的代码中看到了两个问题
newstr = strtok (mystr, " ");
如果您的输入在引号内,这将有问题,例如 “这是一个字符串”
代替
这是一个字符串
""this <-- Here
"is"
"a"
"string"
"
是因为引号内的输入 ""
这可以用
清除newstr = strtok (mystr, "\"| ");
另一个是缓冲区末尾的下一行字符需要 用 NULL 清除,否则你一定会得到 exitra 换行符或引号 在这里
""this
"is"
"a"
"string"
" <-- Here
抱歉回答不完整
fgets(mystr, mysize, stdin);
wholestring(mystr);
/** ensure Next line is no more available **/
if(mystr[strlen(mystr)-1] == '\n')
mystr[strlen(mystr)-1] = '\0';
newstr = strtok (mystr, "\"| ");
关于c - 字符串格式、strtok 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631704/