如果我在终端输入5 5
,按回车键,再按回车键,我想退出循环。
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;
}
显然,该代码并没有为我完成这项工作(是的,我知道有一个缓冲区溢出正在等待发生)。
scanf
不会退出,除非我输入一个字母(或一些非数字、非空白字符串)。如何让 scanf 在读取空行后退出?
最佳答案
使用fgets读取控制台输入:
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;
关于c - 让 scanf 在读取换行符时退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46394336/