This question already has answers here:
Why is strtok changing its input like this?
                                
                                    (3个答案)
                                
                        
                                4个月前关闭。
            
                    
因此该程序除一部分功能外均有效。

我真的不明白为什么它没有输出正确的东西。我也必须使用strtok,strcmp和fgets函数。所以我不能改变那些。

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>

 int main(){

 char a[256];

 while(x==0){//this will loop until the exit cammand is given

 int y = (strcmp(fgets(a, 256, stdin), "exit\n"));
 char* token = strtok(a, " ");
 int numOfTokens = 0;

 if (y == 0){
 exit(0);
 }
 else{
 printf("Line read:%s\n", a);
 printf("Token(s):");
 while(token != NULL){
 numOfTokens +=1;
 printf("\n%s", token);
 token= strtok(NULL, " ");
 }
 printf("%i token(s) read\n", numOfTokens);
 }
 }
 return 0;
 }


因此,一切都从linux终端输入。输出应为:

 `h e l l o//input
 //output as followed
 Line read:h e l l o
 Token(s):
 h
 e
 l
 l
 o
 5 token(s) are read`


但是当我做的事情弄糟的是:Line read:h
我要如何在它打印用户输入的整行的地方

最佳答案

strtok()移到printf()之后。
原因是strtok()更改了其参数,因此您可以打印更改。

代替

... strtok(a, " ") ... ;
... printf("%s", a) ... ;




... printf("%s", a) ... ;
... strtok(a, " ") ... ;

关于c - 我如何获得正确的输出? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58549114/

10-12 18:59
查看更多