问题描述
我知道我问的基本问题。我有问题,使用scanf函数和C程序得到。当过我使用scanf函数,得到不执行。示例如下,
I know i am asking basic question. I am having problem with using scanf and gets in C program. When ever i am using scanf, gets is not performing. The example is below,
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();
}
如果我运行这个程序,得到的是不执行。输入值后。它不是等待输入字符串。输出是输入stringEntered字符串为。但是,如果评论scanf函数,它在等待获取并工作正常输入。因此,任何一个可以告诉我,这里没有我错了。
If i run this program, gets is not performing. After Entering the value. It is not waiting to enter the string. Output is "Enter the stringEntered string is". But if comment the scanf, it waiting for input in gets and working properly. So any one tell me, where did i wrong.
推荐答案
那么,正确的答案在这里很简单:永远不要使用获得
。就这么简单。我甚至被从C11标准中删除。
Well, the "proper" answer here is simple: Never use gets
. It's that simple. I has even been removed from C11 standard.
原因是,你有没有办法来限制输入量,所以无论你的缓冲区有多大保留,用户仍然可以产生足够的输入导致缓冲区溢出。
The reason is, you have no way to limit amount of input, so no matter how big buffer you reserve, user can still generate enough input to cause buffer overflow.
您应该使用与fgets
,如果你正在写标准C.你应该使用函数getline
如果你使用 GCC 的(如MinGW的或在窗口Cygwin的),或与最近的足够的POSIX标准支持任何现代的类Unix操作系统。
You should probably use fgets
, if you are writing standard C. You should use getline
if you use gcc (like MinGW or Cygwin under Window), or any modern Unix-like OS with support for recent enough POSIX standard.
然后实际的问题,而忽略与问题可获得
。问题是, scanf函数
叶包括输入preSS到输入流线的其余部分。一个强大的解决方案是编写一个函数,它将读取输入,直到下一个新行,像这样未经测试的功能:
Then to actual question, ignoring problems with gets
. Problem is, scanf
leaves rest of the line including the enter press into the input stream. One robust solution is to write a function, which will read input until next newline, something like this untested function:
// 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
就可以了,上面只是一个简单的可能性。
There are other solutions, such as reading a line to buffer and using sscanf
on it, above is just one easy possibility.
这篇关于使用scanf函数,同时得到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!