获取scanf函数退出时,它读取一个新行? [英] Get scanf to quit when it reads a newline?
本文介绍了获取scanf函数退出时,它读取一个新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我输入 5
在终端上,preSS进入,preSS再次进入,我想退出循环了。
If I input 5 5
at the terminal, press enter, and press enter again, I want to exit out of the loop.
int readCoefficents(double complex *c){
int i = 0;
double real;
double img;
while(scanf("%f %f", &real, &img) == 2)
c[i++] = real + img * I;
c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1
return i;
}
显然,code未为我做的工作(是的,我知道有一个缓冲区溢出等待发生)。
Obviously, that code isn't doing the job for me (and yes, I know there is a buffer overflow waiting to happen).
scanf函数
不会放弃,除非我的信件(或者一些非数字,而不是空白字符串)类型。我如何获得scanf函数读取一个空行后退出?
scanf
won't quit unless I type in a letter (or some non-numeric, not whitespace string). How do I get scanf to quit after reading an empty line?
推荐答案
使用与fgets读控制台输入:
Use fgets to read console input:
int res = 2;
while (res == 2) {
char buf[100];
fgets(buf, sizeof(buf), stdin);
res = sscanf(buf, "%f %f", &real, &img);
if (res == 2)
c[i++] = real + img * I;
}
c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1
return i;
这篇关于获取scanf函数退出时,它读取一个新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文