Search code examples
c++getline

second getline or other input functions doesnt work when i exceed the array size in input for first getline()


#include <iostream> 
#include <string.h>
#include<stdio.h>
using namespace std;

int main() 
{
char d,a[9],e[9];

cin.getline(a,9);
cin.getline(e,9);
cin>>d;
puts(a);
puts(e);
cout<<d<<endl;
return 0}

when i enter "hey every one" on the output screen, puts(e) prints a blank line and d prints a random character.second getline function and cinfunction is not working because of first getline. Thanks in advance.


Solution

  • You should read some documentation for the stuff you use:

    After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):
    - [...]
    - count-1 characters have been extracted (in which case setstate(failbit) is executed).

    (Emphasize mine)

    So the first getline fails if the input is too long and thus leaves std::cin in a bad (i.e. unreadable) state. This makes all successive input operations fail immediately.


    Remark: To avoid tons of ugly trouble, you should avoid using C-style strings and the "kind of C-style" member-getline and just use std::string and the non-member std::getline instead.