gpt4 book ai didi

c++ - do/while 循环无法正常运行

转载 作者:行者123 更新时间:2023-11-27 23:19:26 27 4
gpt4 key购买 nike

我在让 do/while 循环正常运行时遇到问题。这个程序在第一次复飞时运行良好,但是当我输入'y'时它询问我是否想“告诉更多”程序只是询问用户问题(不允许我输入字符串)然后计算声明。我究竟做错了什么?以及如何让它正常运行?

using namespace std;

int main()
{
int i, numspaces = 0;
char nextChar;
string trimstring;
string uc, rev;
string answer;
char temp;
cout << "\n\n John Acosta"
<<" Exercise 1\n"
<< "\n\n This program will take your string, count the number\n"
<< " of chars and words, UPPERCASE your string, and reverse your string.";

string astring;
do {
cout << "\n\nTell me something about yourself: ";
getline (cin, astring);

trimstring = astring;
uc = astring;
rev = astring;

for (i=0; i<int(astring.length()); i++)
{
nextChar = astring.at(i); // gets a character
if (isspace(astring[i]))
numspaces++;
}


trimstring.erase(remove(trimstring.begin(),trimstring.end(),' '),trimstring.end());
transform(uc.begin(), uc.end(),uc.begin(), ::toupper);

for (i=0; i<rev.length()/2; i++)
{
temp = rev[i];
rev[i] = rev[rev.length()-i-1];
rev[rev.length()-i-1] = temp;
}

cout << "\n\tYou Entered: " << astring
<< "\n\tIt has "<<trimstring.length()
<< " chars and "<<numspaces+1
<< " words."
<< "\n\tUPPERCASE: "<<uc
<< "\n\tReversed: "<<rev
<< "\n\n";


cout<<"\n\nwant to tell me more? Enter \"y\" for YES and \"n\" for NO\n\n";
cin>>answer;
cout<<"\n";

} while(answer == "y"); //contiue loop while answer is 'y'; stop when 'n'

{
cout <<"\n Thanks. Goodbye!\n"; //when loop is done
}

return 0;
}

最佳答案

输入运算符 >>> 是这样工作的:首先它会跳过空格,如果有的话;然后它读取字符串直到到达下一个空格,在您的例子中是 'y' 之后的换行符。然后这个换行符留在流中,所以当您在循环开始时执行 getline 时,您会在 "y" 之后得到换行符。

您可以使用 ignore 删除它功能:

cout<<"\n\nwant to tell me more? Enter \"y\" for YES and \"n\" for NO\n\n";
cin>>answer;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<"\n";

关于c++ - do/while 循环无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14334355/

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