Reputation: 107
Tthe issue is that the part that uses getline()
doesn't take input the first time, it just says "Enter a string: Enter a string:" and then you can put input there.
#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];
}
}
Upvotes: 3
Views: 9015
Reputation: 340436
The problem is that you first use cin >> num;
to read a number, but that's leaving a newline in the stream which the getline()
call reads.
Maybe add a cin.ignore(1,'\n');
after the cin >> num;
to eat that stray newline.
Upvotes: 11