Do/while循环不能正常工作
Do/while loop not functioning correctly
我有一个问题,让我的do/while循环正常工作。这个程序在第一次循环时运行良好,但是当我输入"y"时,当它问我是否想"告诉更多"时,程序只是问用户这个问题(不允许我输入字符串),然后计算语句。我做错了什么?我怎样才能让它正常工作呢?
using namespace std;
int main()
{
int i, numspaces = 0;
char nextChar;
string trimstring;
string uc, rev;
string answer;
char temp;
cout << "nn John Acosta"
<<" Exercise 1n"
<< "nn This program will take your string, count the numbern"
<< " of chars and words, UPPERCASE your string, and reverse your string.";
string astring;
do {
cout << "nnTell 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 << "ntYou Entered: " << astring
<< "ntIt has "<<trimstring.length()
<< " chars and "<<numspaces+1
<< " words."
<< "ntUPPERCASE: "<<uc
<< "ntReversed: "<<rev
<< "nn";
cout<<"nnwant to tell me more? Enter "y" for YES and "n" for NOnn";
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<<"nnwant to tell me more? Enter "y" for YES and "n" for NOnn";
cin>>answer;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
cout<<"n";
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- sdl软件渲染器不工作,工作在硬件加速的一个
- C++程序已停止工作-求解常微分方程