C:第二个FGET的字符错误
我有以下代码:C:第二个FGET的字符错误,c,char,printf,fgets,C,Char,Printf,Fgets,我有以下代码: char temp; scanf("%c",&temp); fgets(variable1,50,stdin); strtok(variable1, "\n"); printf("%s ", variable1); 这将获取一个可能包含空格的字符串,并将其分配给变量variable1。稍后,我可以毫无问题地打印字符串 当我向code otherfgetsfor get other变量中的其他字符串添加代码时,问题就出现了 if (1) { scanf("%c"
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
这将获取一个可能包含空格的字符串,并将其分配给变量variable1
。稍后,我可以毫无问题地打印字符串
当我向code otherfgets
for get other变量中的其他字符串添加代码时,问题就出现了
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
始终工作正常。但是我尝试用%s
variable2
打印一些短语,但结果没有得到第一个字符,只有第二个scanf
。如果我打招呼,variable2
是ELLO
我已经使用另一个temp
变量、另一个数据等进行了测试,但总是得到相同的错误
为什么会这样
更新
了解更多信息。我使用scanf
,因为如果我不使用它,程序在等待字符串时不会暂停。我使用strtok(variable1,“\n”)代码>以删除换行符
此程序位于while
和开关箱中。我把完整的代码:
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;
如果我介绍EquipoHELLO
和PilotoFRIEND
,输出是:
你说你好,朋友
我不理解你的示例代码。你能用你的实际代码更新这个问题吗
我想scanf不应该在那里
这段代码对我来说很好:
char var1[50], var2[50];
fgets(var1, 50, stdin);
strtok(var1, "\n");
printf("Var1: %s\n", var1);
if (1) {
fgets(var2, 50, stdin);
strtok(var2, "\n");
printf("Var2 %s\n", var2);
}
输出:
Test1
Var1: Test1
Test2
Var2 Test2
根据OP最新编辑的帖子和评论重新编写
您描述了只需从用户输入中获取两个字符串,从每个字符串中删除换行符,然后将这两个字符串打包成一条消息,发送到stdout
。如果此描述与您的需要相符,请更改此代码部分:
...
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);
...
为此:
...
printf("enter equipo: ");
if(fgets(equipo, sizeof(equipo), stdin))
{
equipo[strcspn(equipo, "\n")] = 0; //remove newline
printf("enter piloto: ");
if(fgets(piloto, sizeof(piloto), stdin))
{
piloto[strcspn(piloto, "\n")] = 0;
printf("You said %s and %s", equipo, piloto);
}
}
...
注:strtok(piloto,“\n”)代码>可以工作,但如果用户只点击
顺便问一下,scanf(“%c”和&temp)的原因是什么代码>?如果您试图跳过一个换行符,fgets()
已经读到了。请发布一个,包括所有变量声明。您在扫描variable2
后打印variable1
,因此您的variable1
可能不像您想象的那样“正确”。If()
具有printf(“%s”,variable1)代码>。这是真的密码吗?它真的是printf(“%s”,变量2)代码>?如果他们键入的字符超过50个,您希望发生什么?如果我这样做,程序不会暂停等待用户输入的字符串,而是直接选择一个“\n”作为var1
…您应该始终获得fgets@M.M-我想我明白你的意思。错误的功能选择和OP更新后的应答,甚至无法解决主请求。全部重新写入。谢谢