如果我在终端输入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/3723044/