我希望输入带空格的字符串。我使用了 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/