简体   繁体   English

C ++将用户输入的字符串句子存储到向量中

[英]C++ store string sentences from user input into a vector

I am a beginner at C++ and currently learning vectors. 我是C ++的初学者,目前正在学习向量。 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? 1)这背后的原因是什么? Why does user need to enter two strings before going to next loop? 为什么用户在进入下一个循环之前需要输入两个字符串? Can someone explain to me. 有人可以向我解释。

2) how can this be fixed? 2)如何解决?

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. 问题是循环内的ignore调用。

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. std::getline将默默地吃掉尾随的换行符,但是由于您随后调用ignore ,因此必须输入第二行才能使ignore得到满足。

Simply remove the ignore call from the loop and it should work as you expect. 只需从循环中删除ignore调用,它便会按预期工作。

Did you try to put cin.clear(); 您是否尝试放入cin.clear();? cin.sync(); cin.sync(); before getline function? 在getline函数之前? cin and getline give you problems when you use them at the same time. cin和getline在您同时使用它们时会给您带来问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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