[英]Why am i not getting the correct output
我正在编写一段代码来询问格式为P0 xy
的两个特定点。 如果用户输入Q
则程序终止,由于某种原因,我无法将用户输入 ( P0 xy
) 输出到 output 中。 当我尝试运行代码并输入P0 2 3
时,它说我选择了点0 2.00 3.00
。
而所需的 output 是P0 2 3
。
#include <stdio.h>
void main() {
float a, b;
char Q, P, input;
printf("");
scanf("%c", &input);
if (input == 'Q') {
printf("quitting program");
return (0);
} else {
scanf("%c" "%f" "%f", &input, &a, &b);
printf("you have chose points: %c %f %f", input, a, b);
}
return (0);
}
因为你使用了两个scanf
。 首先scanf
读取P
然后第二个scanf
从命令行(从stdin
)读取0
。 所以在第二次scanf
之后, input = '0'
。 这就是您的程序打印0 2.00 3.00
的原因
如果要打印P0
,则必须使用字符串,例如下面的示例:
#include <stdio.h>
int main()
{
float a, b;
char Q, P, input;
char point[3] = {'\0'};
scanf( "%c" , &input);
point[0] = input;
if(input=='Q')
{
printf("quitting program");
return 0;
}
else
{
scanf( "%c" "%f" "%f", &input, &a, &b);
point[1] = input;
printf("you have chose points: %s %f %f",point, a, b);
}
return 0;
}
正如另一个答案还提到的,在输入中检查Q
时,输入字节被消耗。 C 标准库提供了针对此特定问题的修复:您可以将消耗的字节“返回”到输入设备(键盘缓冲区),然后重试从输入读取。
function 是ungetc
。 它需要非常特定的语法(您应该“取消”与刚刚读取的值相同的值;您还必须使用stdin
来指定您正在使用键盘)并且仅适用于一个字节,完全符合您的需要。
这是您的代码以及我的更新和评论。
#include <stdio.h>
int main()
{
float a, b;
char Q; // only used for checking the "quit" condition
char input[10]; // assuming 9 characters + terminating byte is enough
scanf("%c", &Q);
if(Q=='Q')
{
printf("quitting program");
return (0);
}
else
{
ungetc(Q, stdin); // return one byte to the input device
scanf( "%s" "%f" "%f", input, &a, &b); // "%s" read from the input as string now
printf("you have chose points: %s %f %f",input, a, b);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.