gpt4 book ai didi

c++ - 使用空格取消简单循环

转载 作者:行者123 更新时间:2023-11-30 01:26:31 25 4
gpt4 key购买 nike

这是我完成这个简单任务的代码:

Write the code that will read character input from the user until a blank (a space) is entered. Print how many characters were entered. Keep in mind the user may decide to enter a blank as his first character.

为什么空格没有结束循环?

#include <iostream>
using namespace std;

int main(){
char answer;
int count=1;


do{
cout << "please enter number " << count;
cin >> answer;
count++;

}while(answer!=' ');
cout << "you entered " << count-1 << "numbers." << endl;
return 0;
}

最佳答案

默认情况下,cin >> 操作会跳过所有类型的空格。您可以使用 cin >> noskipws;在循环之前禁用空格跳过或使用 cin.get()相反:

cin.get(answer);

你应该知道现在不再跳过换行和回车,所以你必须单独处理它们。此外,您应该检查流状态以对文件结尾作出 react :

do {
cout << "Please enter number " << count << endl;
do {
cin.get(answer);
} while (cin && (answer == '\r' || answer == '\n'));
count++;
} while (cin && answer != ' ');

关于c++ - 使用空格取消简单循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10272284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com