#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?
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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With