简体   繁体   English

std::getline 在接受多个字符串输入时忽略第一个字符,并且在不使用 cin.ignore() 时字符串下标超出范围

[英]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.

相关问题 为什么在 cin.ignore() 之后没有 getline(cin, var) 读取字符串的第一个字符? - Why doesn't getline(cin, var) after cin.ignore() read the first character of the string? getline(cin,string)即使与cin.ignore()一起也不起作用 - getline(cin, string) not working EVEN WITH cin.ignore() getline 删除第一个字符; 删除 cin.ignore(); 没有解决 - getline removes first character; removal of cin.ignore(); does not resolve 为什么 cin.ignore() 忽略我的 getline 输入的第一个字符? - Why is cin.ignore() ignoring the first character of my getline input? 为什么在不使用 getline() 时必须使用 cin.ignore? - why do I have to use cin.ignore when I not using getline()? 为什么我们需要在getline(cin,string)之前使用cin.ignore()? - Why do we need to use cin.ignore() before getline(cin, string)? cin.ignore的getline问题 - getline issues with cin.ignore 的std :: cin.ignore(的std :: numeric_limits <std::streamsize> 使用#include时出现:: max(),&#39;\\ n&#39;)错误 <Windows.h> - std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') error when using #include <Windows.h> C ++ 11-程序截断每个输入的第一个字母[使用:cin.ignore和getline) - C++11 - Program cuts off first letter of every input [Using: cin.ignore and getline) getline 忽略字符串输入的第一个字符 - getline ignores first character of string input
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM