[英]std::getline ignores first character when taking multiple string inputs and string subscript goes out of range when not using cin.ignore()
when i use cin.ignore() i can take all inputs but i'm missing the first character of all strings after the first input.当我使用 cin.ignore() 时,我可以接受所有输入,但在第一个输入之后我丢失了所有字符串的第一个字符。
If I don't use cin.ignore() I'm getting a string subscript goes out of range run time error如果我不使用 cin.ignore() 我得到一个字符串下标超出范围运行时错误
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.我注释掉代码“
std::cin.ignore();
”,程序运行正常。 The function getline
will discard the char '\n'. function
getline
将丢弃 char '\n'。
I test these codes you provided, if I comment out cin.ingnore, it run properly.我测试了你提供的这些代码,如果我注释掉 cin.ingnore,它运行正常。 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.也许你应该检查你的代码,看看是否还有其他错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.