how to input a string with spaces in c++?
char ch[20];
cin>>t;
while(t–)
{
cin.getline(ch,20);
cout<<ch<<endl;
}
the abv code is not working…
if using string then getline(cin,s); and if using character array as you are using in the example above use fgets(ch,20,stdin).please see what headerfile you need to include i don’t remember because i use bits/stdc++.h
you mush not have added getchar before while loop like this `
char ch[20];
cin>>t;
getchar();
while(t–)
{
}
`
when we have to input string after an integer input we do like this because of neither cin nor scanf reads the left ‘\0’ so we add getchar(); or char a;cin.get(a) to read that left ‘\0’;
You could just create a loop asking for input to each element in a char array. The program won’t accept whitespace, and will move to the next input. It would look something like this:
char letters[20];
for (int i = 0; i < n; i++){
cin >> letters[i];
}
fgets and get line both are not working
#include
#include<stdlib.h>
using namespace std;
int main()
{
int t;
int count[26];
cin>>t;
getchar();
char text[201];
while(t–)
{
for(int i=0;i<26;i++)
count[i]=0;
fgets(text,201,stdin);
cout<<text<<endl;
}
return 0;
}
this is still printing an extra newline after every output???