【发布时间】:2020-09-08 12:20:24
【问题描述】:
我有这个代码:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
这会得到一个可能包含空格的字符串并将其分配给变量variable1。之后,我可以毫无问题地打印字符串。
当我在代码中添加其他 fgetsfor 获取其他变量中的其他字符串时,问题就出现了。
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
完成的结果是:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
variable1 始终正常工作。但我尝试用%svariable2 打印一些短语,但结果没有得到第一个字符,只有第二个scanf。如果我打招呼,variable2 就是 ELLO。
我已经使用另一个temp 变量、另一个数据等进行了测试。但总是得到同样的错误。
为什么会这样?
更新
了解更多信息。我使用scanf,因为如果我不使用它,程序在等待字符串时不会暂停。我使用strtok(variable1, "\n"); 删除换行符。
该程序位于while 和switch case 中。我放了完整的代码:
case 4: printf( "Put equipo: ");
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
}
break;
如果我像 Equipo HELLO 和 Piloto FRIEND 这样引入,输出是:
You said HELLO and RIEND
【问题讨论】:
-
scanf("%c", &temp);的原因是什么?如果你想跳过换行符,fgets()已经读到了。 -
请发minimal reproducible example,包括所有变量声明。
-
您在扫描
variable2后打印variable1,因此您的variable1可能不像您想象的那样“正确”。 -
if()有printf("%s ", variable1);。那是真正的代码吗?真的是printf("%s ", variable2);吗? -
如果他们输入的字符超过 50 个,您希望发生什么?