获得第一个字符串并且第一个双重后,程序没有得到其他字符串。
for (int i = 0; i< NUM_MOVIES; i++)
{
cout << "Enter the name of the movie: ";
getline(cin, names[i]);
cout << "How much did " << names[i] << " earn <in millions>: ";
cin >> earnings[i];
cout << endl;
}
答案 0 :(得分:4)
第二次拨打getline
时,您实际上正在阅读换行符,因为cin >>
在刚刚读取的值之后不会丢弃换行符。
所以你最终会在这个阅读不良数据的循环中结束。试试这个:
getline(cin >> std::ws, names[i]);
答案 1 :(得分:1)
cin >> earnings[i];
这应该纠正如下
getline(cin, earnings[i])
//示例程序
#include <iostream>
#include <string>
using namespace std;
int main()
{
string names[10];
string earnings[10];
for (int i = 0; i< 10; i++)
{
cout << "Enter the name of the movie: ";
getline(cin, names[i]);
cout << "How much did " << names[i] << " earn <in millions>: ";
getline(cin, earnings[i]);
cout << endl;
}
cout<< names[0]<< names[1]<<"\n";
cout<<earnings[0] << earnings[1]<<"\n";
return 0;
}
答案 2 :(得分:1)
问题是>>
没有读过行尾,所以下面的std::getline()
会这样做,而不是抓住你的下一个输入。
您可以使用std::ws
(吸收空白字符):
for (int i = 0; i< NUM_MOVIES; i++)
{
cin >> std::ws; // clear previous line
cout << "Enter the name of the movie: ";
getline(cin, names[i]);
cout << "How much did " << names[i] << " earn <in millions>: ";
cin >> earnings[i];
cout << endl;
}