Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C printf()生成垃圾_C_Printf - Fatal编程技术网

C printf()生成垃圾

C printf()生成垃圾,c,printf,C,Printf,我想提取输入字符串的第一个和第二个单词。我不明白为什么printf语句会产生垃圾输出替换scanf%s,username;与getsusername;第3行。 这就是你的问题所在。Scanf只接受第一个字。请永远记住,printf不会产生任何垃圾。是我们自己创造了这些问题。在使用字符串时,请务必小心,为了指示printf字符串的结尾,我们必须在字符串的结尾处放置一个字符串的结尾字符,这称为空字符\0或0。有些C函数没有在字符串末尾插入\0字符,因此我们有责任处理它。最好总是在下面这样的所有位置用

我想提取输入字符串的第一个和第二个单词。我不明白为什么printf语句会产生垃圾输出

替换scanf%s,username;与getsusername;第3行。
这就是你的问题所在。Scanf只接受第一个字。

请永远记住,printf不会产生任何垃圾。是我们自己创造了这些问题。在使用字符串时,请务必小心,为了指示printf字符串的结尾,我们必须在字符串的结尾处放置一个字符串的结尾字符,这称为空字符\0或0。有些C函数没有在字符串末尾插入\0字符,因此我们有责任处理它。最好总是在下面这样的所有位置用0初始化字符串,这是避免这样的副作用的良好实践之一

char username[50];

printf("[Enter Command]: \n");
scanf("%s", username);

if (strcmp("exit", username) == 0) {
    exit(0);
}

if (strcmp("jobs", username) == 0) {
    printf("[SERVER] No currently running jobs\n");
}

char dtm[50];
char first_word[50];
char second_word[50];


strcpy(dtm, username);
sscanf(dtm, "%s %s", first_word, second_word);

printf("%s %s\n", first_word, second_word);
下面的练习也是安全的

char dtm[50];
char first_word[50];
char second_word[50];

memset(dtm, 0, 50);//or memset(dtm, 0, sizeof(dtm));
memset(first_word, 0, 50);//or memset(first_word, 0, sizeof(first_word));
memset(second_word, 0, 50);// or memset(second_word, 0, sizeof(second_word));

所有调用函数的返回值是多少?请升级到a。如果dtm只包含一个字,则第二个字是垃圾,是的。检查scanf的返回值。它必须是2。您知道%s格式停止在空格上吗?也许你想读一整行?我投票结束这个问题,因为OP不能拼写garbageDo不建议使用不推荐使用的函数get,你应该建议使用fgetsmemset works,但它是OTT。char dtm[50]=;读起来更好。是的,没错。谢谢你的评论。我根据你的建议修改了我的答案。
char dtm[50] = "";
char first_word[50] = "";
char second_word[50] = "";