Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin.getline( ) with larger size

Tags:

c++

getline

#include<iostream>
using namespace std;

int main()
{
   char test[10];
   char cont[10];

   cin.getline(test,10);
   cin.getline(cont,10);

   cout<<test<<" is not "<<cont<<endl;
    return 0;
}

When I input:

12345678901234567890

output is:

123456789

It seems cont is empty. Could someone explain it?

like image 826
deryk Avatar asked May 19 '11 04:05

deryk


2 Answers

istream::getline sets the fail bit if the input is too long, and that prevents further input. Change your code to:

#include<iostream>
using namespace std;

int main()
{
   char test[10];
   char cont[10];

   cin.getline(test,10);
   cin.clear();                    // add this
   cin.getline(cont,10);

   cout<<test<<" is not "<<cont<<endl;
    return 0;
}
like image 138
andrewdski Avatar answered Sep 30 '22 07:09

andrewdski


If the variable you read into isn't big enough to hold the entire line, the input operation fails and the stream will not read anything more until you call cin.clear().

You should use a std::string instead to hold the data. It will resize itself to match the input.

std::string test;
std::string cont;

getline(cin, test);
getline(cin, cont);
like image 28
Bo Persson Avatar answered Sep 30 '22 06:09

Bo Persson