Akram Mohammed
Akram Mohammed

Reputation: 151

How should the cin.ignore() function be used in this code?

My goal is to solve this:

Given a string S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line

int main() {

    int test;
    cin>>test;
    for(int j = 0; j < test; j++){

        char str[10000];
        cin.ignore();
        cin.getline(str,9999);
        for( int i = 0; i < strlen(str); i++)
        {
            if(i % 2 == 0)
                cout<<str[i];
        }
        cout <<" ";
        for(int i = 0; i < strlen(str); i++)
        {
            if((i % 2 != 0))
                cout<<str[i];
        }

        cout << endl;
    }

    return 0;
}

The above code gives me output as :

Hce akr 
ak n 

for the given input of:

2 
Hacker
Rank

But when I use cin>>str instead of the cin.ignore() and cin.getline(), I get the correct expected output: How does that change the result?

Hce akr 
Rn ak

Upvotes: 1

Views: 1099

Answers (2)

Grim Firefly
Grim Firefly

Reputation: 46

You should Write cin.ignore(); before for loop . Your code ignoring first charecter of every string without first iteration. You need to ignore line break for only test not for every string .

see the below code :

int main() {

    int test;
    cin>>test;
    cin.ignore();
    for(int j = 0; j < test; j++){

        char str[10000];
        cin.getline(str,9999);
        //cin>>str;

        for( int i = 0; i < strlen(str); i++)
        {
            if(i % 2 == 0)
                cout<<str[i];
        }
        cout <<" ";
        for(int i = 0; i < strlen(str); i++)
        {
            if((i % 2 != 0))
                cout<<str[i];
        }

        cout << endl;
    }

    return 0;
}

input :
5
Hacker
Rank
WoW
check
lastone

output :
Hce akr
Rn ak
WW o
cek hc
lsoe atn

Upvotes: 3

Remy Lebeau
Remy Lebeau

Reputation: 598448

Using ignore()+getline():

On the first loop iteration, cin.ignore() skips the line break that was left behind from cin>>test, then cin.getline() reads the entire line (Hacker) including but swallowing the line break.

On the second loop iteration, cin.ignore() skips the 1st character of the next line (R), and then cin.getline() reads the remaining characters of the same line (ank) including but swallowing the line break.

The solution is to move the call to cin.ignore() to above the loop:

cin>>test;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- move here

for(int j = 0; j < test; j++){
    char str[10000];
    cin.getline(str,9999);
    ...
}

Using operator>>:

On the first loop iteration, cin>>str skips the line break that was left behind from cin>>test and then reads the next available word (Hacker).

On the second loop iteration, cin>>str skips the line break that was left behind from the previous cin>>str and then reads the next available word (Rank).

Upvotes: 1

Related Questions