c - gets() 似乎存储了一些垃圾字符串

标签 c

我希望输入带空格的字符串。我使用了 gets(),已经处理了换行符 [使用 while( (c = getchar()) != '\n' && c != '\0'); ]制造问题。但是第一个 gets() 输入了一些杂散字符!另外,如果我使用 scanf( "%[^\n]s", a) 而不是 gets() ,则会存储一些随机字符串!有人可以帮我找出原因吗?

这是代码:

printf(" \n Enter the string");
while( (c =getchar()) != '\n' && c != '\0');
gets(a); // some garbage string is stored in a....if i replace it with scanf()...then                    also garbage string is stored 

printf(" \n The ENTERED  string is %s", a);


printf("\n Enter the substring to be extracted (max 20)  ");
while( (c =getchar()) != '\n' && c != '\0');
gets(sub);

最佳答案

这对我有用;我使用了一个短缓冲区来检查如果输入字符串溢出输入缓冲区,不会发生任何不良情况(溢出由 stdin 缓冲到下一次调用 fgets,如预期的那样)来自流)。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char a[32];
    for (;;) {
            printf("Enter the string:\n");
            fgets(a, sizeof(a), stdin);
            strtok(a, "\r\n");
            printf("The entered string is '%s'\n", a);
    }
}

关于c - gets() 似乎存储了一些垃圾字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298347/

相关文章:

c - C 标准中定义的短语 "declaration of"在哪里,否则应该如何解释它?

c - 将矩阵的一行乘以给定的数字

c - 如何正确验证 scanf 中读取了多少输入

c - open_memstream 警告 "pointer from integer without a cast"

c - 为什么我收到 "unresolved external"错误?

c - `PAGE_ALIGN` 和 `unsigned int` 有什么作用?它不应该得到一个地址吗?

创建/初始化共享内存中的对象(由mmap()打开)

c - 如何使用 Escape 键结束 C 中的循环

c++ - 编译器有时可以缓存声明为 volatile 的变量吗

c++ - ImageMagick 使用我的真实字体 (Magick++) 转换 SVG