Hi guys, I was making a program a few months ago in C++ and in this program I used cin.getline but I found if I used this more than once in the same function some of the cin.getlines would be ignored once the program was compiled.

I was just wondering if anyone has any idea why this happens?

Thanks in advance.

Dani AI

Generated

Most common cause: a leftover newline in the input buffer. Mixing formatted extraction (for example std::cin >> someInt;) with cin.getline causes the formatted extraction to stop at the number but leave the trailing '\n' in the stream, so the next getline immediately reads that empty line. ’s pointer to the MSVC6 KB is relevant — MSVC6’s iostreams had known quirks — but the usual fix is to flush the newline or use std::getline consistently.

Example fixes (use <limits> and <string>):

#include <iostream>
#include <string>
#include <limits>

int main() {
    int n;
    std::cin >> n;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard remainder of line

    std::string line;
    std::getline(std::cin, line); // now reads the full next line
}

Or avoid mixing extraction styles:

std::string token;
std::getline(std::cin, token); // use this for everything, then parse token if needed

Troubleshooting notes: if two back-to-back getline calls (with no >> in between) still behave oddly, that points to the compiler/library bug that mentioned. To isolate that, build a tiny test that calls getline twice; if it only fails under MSVC6 and works with a newer compiler, the MSVC6 bug is the culprit. Otherwise, inserting a cin.ignore(...) after formatted input will resolve the “skipped getline” symptom.

Recommended Answers

All 4 Replies

Are you using MSVC6?

Yeah thats what I was using.

Thanks for the link.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.