我在用 c 语言读取字符串时遇到了问题。当我在 if 指令中添加 gets() 函数时,程序停止。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n,i = 0;
char sir[2000],ch;
printf("Press you option: "); scanf("%d",&n);
if(n == 1)
{
printf("text: "); gets(sir);
printf("\nINPUT: ");
for(i = 0;i < strlen(sir);i++)
printf("%c",sir[i]);
}
return 0;
}
有什么解决办法吗?
最佳答案
When I add the gets() function in an if-instruction, the program stops.
看看前面的代码。也许你输入了 1 Enter
printf("Press you option: ");
scanf("%d",&n);
scanf("%d",&n);
消耗 '1'
, 但不是 '\n'
.
后面的代码做
printf("text: ");
gets(sir);
然后 gets()
读到 '\n'
并返回 sir[0] == '\0'
,一个空字符串。这导致 for(i = 0;i < strlen(sir);i++)
不迭代 for()
的主体循环。
怎么办?
读取用户输入的行 fgets()
然后处理该字符串。请注意,此简单代码示例中未解决无效输入、EOF 和缓冲区溢出处理。那将是第 2 步。
char buf[80];
printf("Press you option: ");
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%d",&n);
printf("text: ");
fgets(buf, sizeof buf, stdin);
buf[strcspn(buf, "\n")] = '\0'; // lop off potential \n
strcpy(sir, buf);
关于c - 在 if 指令中读取 c 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41448967/