下次不会让我通过 while (true) 循环输入信息
Won't let me enter information next time through the while (true) loop
第一次迭代将正常工作。我可以输入歌曲标题、艺术家和评级。但是,下次它将显示"输入歌曲标题"和"输入艺术家:",这意味着我下次无法输入歌曲标题。我确定这是一个简单的错误,但我找不到它。这是C++。
#include <iostream>
using namespace std;
void printResults(double ratingOfSong);
int main(void)
{
bool getInput = true;
char song[256];
char artist[256];
cout << "Thank you for taking the time to rate different songs." << endl
<< "This will better improve our quality to better serve you." << endl
<< "Please enter song title, artist, and a rating out of 5 stars." << endl << endl << endl;
while ( getInput )
{
cout << "Enter song title - XYZ to quit: ";
cin.getline(song,256);
if ( song[0] == 'X' && song[1] == 'Y' && song[2] == 'Z')
{
getInput = false;
cout << "Thank you for taking the time in rating the songs." << endl;
break;
}
else
{
double rating = 0;
cout << "Enter artist: ";
cin.getline(artist,256);
cout << "Enter rating of song: ";
cin >> rating;
printResults(rating);
}
}
}
void printResults(double ratingOfSong)
{
if (ratingOfSong <= 1.5)
{
cout << "We are sorry you didn't like the song. Thanks for the input." << endl << endl;
}
else if (ratingOfSong > 1.5 && ratingOfSong <= 3.0)
{
cout << "We hope the next song you buy is better. Thanks for the input." << endl << endl;
}
else if (ratingOfSong > 3.0 && ratingOfSong <= 4.0)
{
cout << "We are glad that you somewhat enjoy the song. Thanks for the input." << endl << endl;
}
else if (ratingOfSong > 4.0 && ratingOfSong < 5.0)
{
cout << "We are glad that you like the song! Thanks for the input." << endl << endl;
}
else if (ratingOfSong >= 5.0)
{
cout << "A perfect score, awesome! Thanks for the input." << endl << endl;
}
}
您需要丢弃上次输入操作中流中留下的新行。为此使用std::cin.ignore()
:
std::cout << "Enter song title - XYZ to quit: ";
std::cin.ignore(); /*
^^^^^^^^^^^^^^^^^^ */
std::cin.getline(song, 256);
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 对于完成布尔值设置为 true 后未停止的循环
- C++ if 语句将条件设置为 true 和循环中的 OR-ing 条件之间的行为差异
- 即使初始要求为 true,也不会输入 for 循环
- 初始化时 num 的哪个值会给这个嵌套循环一个"true"输出?
- 当 c++ 布尔函数返回 true 时无限循环
- 为什么我在图中的DFS循环检测总是返回true
- 了解 While(true) 循环
- 下次不会让我通过 while (true) 循环输入信息
- 如果 else 语句循环或重复,直到 true
- 而循环在为假时计算为 true C++
- 如何编写条件 for 循环(如果 true 循环通过 A,否则循环通过 B)
- 为什么这个 while 循环永远不会计算为 true
- 如何在布尔值(false和true)上编写“for”循环
- While循环为true false,不加增量
- 如果是字符或字符串返回false,但如果输入不能转换为整数则返回true.c++的while循环
- 我们是否可以创建一个类似scanf的函数,当所有参数都填充时返回true,否则返回false,而不循环遍历所有变量?
- 无限"true" while 循环