Strings with spaces in a while loop??

#include<bits/stdc++.h>
#include

using namespace std;

int main()
{
char s[1000];
int n;
cin>>n;

 while(n--)
 {
      cin.ignore();
      fgets(s,1000,stdin);
      cout<<s;
      //display(0,s);
      cout<<"\n";
 }

}

//This is taking wrong input as first one is correct but in the following one’s the first letter gets deleted how to fix this???

cin.ignore() extracts a character from input stream and discards it, so if there was an extra newline character in stream, it would have discarded it.

However in case of fgets the newline character does not remain in the input stream as the new line character gets copied on to your final string. So when you call cin.ignore(), the next character in input sequence is discarded.

So your output is as follows:

Input:

3

test case

hello world

a b c

Output:

test case

ello world

b c

So to solve this, you can use

cin.getline(s,1000);

Hope this helps!

1 Like

nope… The program is still discarding the first character of s

nope… The program is still discarding the first character of s

#include
#include <bits/stdc++.h>
using namespace std;

int main() { char s[1000]; int n; cin>>n;
cin.ignore();
while(n–)
{
cin.getline(s,1000);
cout<<s;
//display(0,s);
cout<<"\n";
}
}

//See this

cin.ignore() has to be called only once before the loop, and not in the following iterations, as the newline character is no longer present and thus nothing has to be ignored

If it helped, please upvote me so that I can ask questions