Santhosh R
Santhosh R

Reputation: 31

Problem with getline() function when reading character array

In my I am reading two character arrays ch1[5] and ch2[10]. Problem is when I enter ch1 more than 5 characters then I can't able to enter ch2. ch2 takes newline Character automatically. To ignore newline character I used cin.ignore() function but still it's not working.

    #include<iostream>
    #include<cstring>
    using namespace std;

    int main()
    {
        char ch1[5],ch2[10];
        cout<<"String Comparision :\n";
        cout<<" Enter strings 1 : ";
        cin.getline(ch1,5);
        cin.ignore();
        cout<<"Enter strings 2 : ";
        cin.getline(ch2,10);
        cout<<"Compairing... \n";
        if(strcmp(ch1,ch2))
             cout<<"Two Strings are Same";
        else cout<<"Two Strings are not Same";

        return 0;
     }

Upvotes: 0

Views: 322

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117348

If you enter more than 4 characters in cin.getline(ch1,5);, failbit will be set on the stream. This prevents reading the stream afterwards - unless you first call cin.clear();.

Note: cin.ignore() does not ignore the newline in your case. cin.getline will already extract and discard the newline, so your cin.ignore() will instead remove the first character in the next line the user enters. What you could do is something like this:

#include <limits>

//...

cout<<" Enter strings 1 : ";
if(not cin.getline(ch1, 5)) {  // check if reading didn't work properly
   if(cin.eof()) return 1;     // cin was closed, exit

   cin.clear();                // clear failbit

   // ignore the rest of the long line
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
cout<<"Enter strings 2 : ";
//...

Note 2: You've got a bug in the strcmp logic. std::strcmp returns 0 if the C strings are equal.

Upvotes: 1

Related Questions