我知道我在问基本问题。我在 C 程序中使用 scanf
和 gets
时遇到问题。当我使用 scanf
时,gets
没有执行。示例如下:
void fun() {
char str[10];
printf("Enter the string");
gets(str);
printf("Entered string is %s\n", str);
}
int main() {
int val;
printf("Enter the value\n");
scanf("%d", &val);
fun();
}
如果我运行这个程序,gets
不会执行。输入值后。它不等待输入字符串。输出为 Enter the stringEntered string is
。但是如果注释 scanf
,它会等待 gets
中的输入并正常工作。谁能告诉我,我做错了什么。
最佳答案
嗯,这里的“正确”答案很简单:永远不要使用 gets
。就这么简单。它甚至已从 C11 标准中删除。
原因是,你没有办法限制输入的数量,所以无论你保留多大的缓冲区,用户仍然可以产生足够的输入来导致缓冲区溢出。
如果您正在编写标准 C,您可能应该使用 fgets
。如果您使用 gcc(如 MinGW 或 Cygwin),您应该使用 getline
在 Window 下),或任何支持最新 POSIX 标准的现代类 Unix 操作系统。
然后是实际问题,忽略 gets
的问题。问题是,scanf
将包括 enter press 在内的行的其余部分留在了输入流中。一个强大的解决方案是编写一个函数,它将读取输入直到下一个换行符,类似于这个未经测试的函数:
// this function reads given file until newline or end of file or error,
// and returns last value read
int eatLine(FILE *fp) {
for(;;) {
int ch = getc(fp);
if (ch == '\n' || ch < 0) return ch;
}
}
用法:
if (scanf("%d", &myint) != 1) exit(0); // exit on invalid input
if (eatLine(stdin) < 0) exit(0); // read and ignore rest of the line, exit on eof
还有其他解决方案,例如读取一行缓冲并对其使用sscanf
,以上只是一种简单的可能性。
关于c - 同时使用 scanf 和 gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26815982/