问题是使用 getline()
的部分第一次没有接受输入,它只是说“输入一个字符串:输入一个字符串:”然后你可以在那里输入.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[100], key=0, num = 0;
while(num != -1)
{
cout << "Enter a positive integer (-1 to exit): ";
cin >> num;
if(num != -1)
{
nums[key] = num;
key++;
}
}
if(num != -1)
{
nums[key] = num;
key++;
}
int numElements = key;
string inStrings[100];
for(int i=0; i < numElements; i++)
{
cout << "\n";
cout << "Enter a string: ";
getline(cin, inStrings[i]);
}
for(int i=0; i < numElements; i++)
{
cout << nums[i] << " :: " << inStrings[i];
}
}
最佳答案
问题是您首先使用 cin >> num;
读取数字,但这会在 getline()
调用读取的流中留下换行符。
也许在 cin >> num;
之后添加一个 cin.ignore(1,'\n');
来吃掉那个流浪的换行符。
https://stackoverflow.com/questions/10311382/