Strings with spaces in a while loop??

questions

#1

#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<<"

";
}
}

//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???


#2

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!


#3

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


#4

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


#5

#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<<"
";
}
}

//See this


#6

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


#7

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