Question

Hello so i have a problem with the spaces in c++ check this

char inp[10000];
char outp[10000];
int i;
cin >> inp;
for(i=0;i<=strlen(inp);i++)
{
  outp [i] = inp[i];
  cout << outp[i];
}

So if i run this and type: Hello stackoverflow the output will be: Hello. Any help will be appreciated , also this is just a part of the code.

Was it helpful?

Solution 2

cin>> just takes the word until it encounters \0

cin.getline(name of string, string size) takes the words until it encounters \n

\0 - Null character, it is there in every string of continues letters.
\n - New line character, it is there when a line ends, (a line consists generally of 80 characters).

So, in your code you have used cin>> which makes your program to only take a single word and not more than that.
Try using cin.getline(name of string, size of string) instead which will make your code work accordingly.

OTHER TIPS

std::cout separate words by white spaces (normally), you can use std::getline instead.

std::getline(std::cin, inp);

And, it's better to use std::string for strings rather that array of characters.

Firstly, why are you using arrays of chars instead of std::string? Much cleaner to use strings unless you have a VERY good reason for using arrays of chars. Secondly, if you want to read in a variable amount of words and save each of them individually (which it seems like you might be trying to do), try this:

std::string output[10000];
std::string inp;
int i = 0;
while (cin >> inp){
   output[i] = inp;
   i++;
}

This will read all your words and store each one in a separate index in output. Hope this helps!

When you use the >> operator of cin, it takes the first token of a string separated by spaces. Hence, saying:

cin >> input; // where input is "hello 12 years"

... is exactly the same with

std::getline( cin, input, ` `);

To get the entire "sentence" that the user enters in the console, you have to use std::getline without the separator parameter:

std::getline( cin, input );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top