简体   繁体   中英

C++ store string sentences from user input into a vector

I am a beginner at C++ and currently learning vectors. Here is a simple code where program gets the user input and stores it in a vector then proceed to print the stored values from each element:

int main(){
vector<string> myVector;
string myInput;
int n;
cin>>n;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
for(int i = 1; i <= n;i++){
  cout<<"loop count: "<<i<<endl; //added for checking the current loop
  getline(cin, myInput);
  cin.ignore(numeric_limits<streamsize>::max(),'\n');
  myVector.push_back(myInput);
  }
for(unsigned int j = 0;j < myVector.size(); j++){
cout<<myVector[j]<<endl;
}
return 0;
}

but when I run my code, during the user string input, it lets me enter two strings before finally going to the next loop. the program only prints out the first entered string for each loop though. So my questions are:

1) What is the reason behind this? Why does user need to enter two strings before going to next loop? Can someone explain to me.

2) how can this be fixed?

EDIT: Here are my sample inputs and the output:

input:

3
input loop count: 1
we are
the champions
input loop count: 2
no time
for losers
input loop count: 3
we are
the champions

output:

we are
no time
we are

The problem is the ignore call inside the loop.

The std::getline will silently eat up the trailing newline, but since you then call ignore you must enter a second line for ignore to be satisfied.

Simply remove the ignore call from the loop and it should work as you expect.

Did you try to put cin.clear(); cin.sync(); before getline function? cin and getline give you problems when you use them at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM