when i use cin.ignore() i can take all inputs but i'm missing the first character of all strings after the first input.
If I don't use cin.ignore() I'm getting a string subscript goes out of range run time error
Here's the code for reference
std::vector<std::string> input;
for (int i = 0; i < 5; i++)
{
std::string lines;
std::cin.ignore();
std::getline(std::cin,lines,'\n');
input.push_back(lines);
}
What do you mean "getting a string subscript goes out of range run time error"? I comment out the code" std::cin.ignore();
", the program run properly. The function getline
will discard the char '\n'.
I test these codes you provided, if I comment out cin.ingnore, it run properly. Here is code:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
std::vector<std::string> input;
for (int i = 0; i < 5; i++)
{
std::string lines;
//std::cin.ignore();
std::getline(std::cin, lines, '\n');
input.push_back(lines);
}
for (auto s : input) {
cout << endl << s;
}
}
Maybe you should examine your codes, and find if there are some other bugs.
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.