Why getline() skipping input, even after cin.clear()?
Asked Answered
N

5

12

So I have a function that keeps skipping over the first getline and straight to the second one. I tried to clear the buffer but still no luck, what's going on?

void getData(char* strA, char* strB)
{
    cout << "Enter String 1: ";               // Shows this line
    cin.clear();
    cin.getline(strA, 50);                    // 50 is the character limit, Skipping Input

    cout << endl << "Enter String 2: ";       // Showing This Line
    cin.clear();
    cin.getline(strB, 50);                   // Jumps Straight to this line
}
Narbonne answered 29/8, 2012 at 21:9 Comment(1)
Is your console less than 50 character-wide ? Default is 80 i thinkPlaybook
M
23

Make sure you didn't use cin >> str. before calling the function. If you use cin >> str and then want to use getline(cin, str), you must call cin.ignore() before.

string str;
cin >> str;
cin.ignore(); // ignores \n that cin >> str has lefted (if user pressed enter key)
getline(cin, str);

In case of using c-strings:

char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);

ADD: Your wrong is not probably in the function itself, but rather before calling the function. The stream cin have to read only a new line character \n' in first cin.getline.

Madeline answered 29/8, 2012 at 21:12 Comment(0)
K
1

cin.clear(); clears any error bits on the stream - it does not consume any data that may be pending.

You want to use cin.ignore() to consume data from the stream.

Karli answered 29/8, 2012 at 21:23 Comment(0)
S
0

After you read something there is still 'RETURN' character inside bufor so you have to cin.ignore() after each read.

You can also use cin.sync() to clear the stream. Actualy clear method only clears flags.

There is also option that you can go to the end of stream, with nothing left to read you should write without problems.

std::cin.seekg(0, std::ios::end);

It is up to you what will you use.

Stifle answered 29/8, 2012 at 21:18 Comment(0)
B
0

use cin.ignore(-1);It will not remove the first character of the input string

Bleed answered 28/4, 2014 at 19:38 Comment(0)
H
0

after a bigger input using get line, a cin causes errors. So using this code after getline returns the input queue and fall bit to normal.

cin.getline(a,5);
    while(getchar()!='\n');
    cin.clear();

that is run a while loop to remove all characters from the queue cin.ignore() causes problem for further inputs and cin.clear() is just to reset the fallbit

Haun answered 15/5, 2021 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.