C++ 为什么fflush(stdin)对输出没有影响?
我编写了这个简单的加法软件,我想在用户输入“n”时结束加法。我目前的代码运行得很好。但是我对同一个代码又做了两个变体,一个有效,另一个给了我一个错误。有人能告诉我每种情况下到底发生了什么吗C++ 为什么fflush(stdin)对输出没有影响?,c++,C++,我编写了这个简单的加法软件,我想在用户输入“n”时结束加法。我目前的代码运行得很好。但是我对同一个代码又做了两个变体,一个有效,另一个给了我一个错误。有人能告诉我每种情况下到底发生了什么吗 int a, b=0; cout<<"Welcome to my Addition Software!!\n\n"; do{ cin>>a; b+=a; }while(getchar()!='n'); cout<&l
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//works just fine
inta,b=0;
库塔;
b+=a;
}while(getchar()!='n');
首先,最好使用C++标准输入和输出<代码> STD::CIN < /C>和
代码的主要问题是它与您想要的类型冲突:
您希望将整数int
相加,并查看输入是否为字符char
'n'
正在发生的是传统的Cfflush(stdin)
会“刷新”或清除标准输入流缓冲区(请在此处阅读更多内容:),并且getchar()
会从用户接收字符输入getchar()
返回一个字符,通过演绎,您的代码将输入的字符转换为其整数int
ASCII-ANSI等效数值积分
这意味着在第三个版本中,当您输入“30”时,实际收集的是“3”,并且在不刷新缓冲区的情况下,下一个输入被视为“0”,从而导致问题
我建议您使用控制结构来检查用户是否希望在收到要添加的输入之前继续:
int a = 0, b =0;
char c = 0; // for y/n responses
std::cout << "Welcome to my ... "; //just finish this string
do{
std::cout << "input integer: "; // for better formatting leave at least one space after the colon
std::cin >> a;
b += a;
std::cout << "Continue? n to stop: "
std::cin >> c;
} while (c != 'n')
std::cout << "Added: " << b;
inta=0,b=0;
字符c=0;//是/否响应
std::cout a;
b+=a;
std::cout>c;
}而(c!=“n”)
std::cout input是20,30,50,n
或20,30,50 n
?这是一种实现定义的行为,跨平台不一致。@iBug实际上是未定义的behaviour@M.M不过,POSIX对此进行了定义,因此在任何macOS或Linux上,它都具有可靠的行为。谢谢。你能解释一下另外两个吗?我将非常感激。问题是,我想省略y/n结构。
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
a=getchar();
b+=a;
}while(a!='n');
cout<<b;
//doesn't work
int a = 0, b =0;
char c = 0; // for y/n responses
std::cout << "Welcome to my ... "; //just finish this string
do{
std::cout << "input integer: "; // for better formatting leave at least one space after the colon
std::cin >> a;
b += a;
std::cout << "Continue? n to stop: "
std::cin >> c;
} while (c != 'n')
std::cout << "Added: " << b;