c - 在 if 指令中读取 c 中的字符串

标签 c string if-statement

我在用 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/

相关文章:

c - 如何从 C 中的标准输出读取

c - 从C中的字符串中提取url

c - 具有灵活数组成员的结构体的 “Array”

java - 将 xml 转换为 json 而不转换字符串/整数?

c++ - 如何将用户从控制台输入的内容读入 Unicode 字符串?

batch-file - 如何更改 IF 语句中的当前目录并使用环境变量 CD 引用其路径?

Javascript 条件运算符没有按我想象的方式运行

c++ - C/C++ 将字符串放入二维数组?

python - 将列表中相似的字符串分组在一起

java - 判断一个数是否是质数