1

I have an exercise to write a program that receives a sentence and then takes from each word the first letter and creates a new word.

My code:

int main(){

char* str = new char[50];

for (int i = 0; i < 50; i++)
    str[i] = NULL;

cin >> str; 

cout<<str;

for (int i = 0; i < 50; i++) 
    cout << str[i]; 


system("pause");
return 0;
} 

But when I want to print the sentence it prints only the first word.

input: 
abcdef abc des

output: 
abcdef abc des
abcdef *******************************************

And when I press a space what goes into the array? How can I know when I'm running on the array with the FOR loop When do I get to the Character where there is space?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Liran
  • 37
  • 1
  • 4

2 Answers2

3

cin >> str; stops when it finds a space character.

use this to read the whole line:

std::string myStr;
std::getline( std::cin, myStr);

Note: You'll have to include <string>

jpo38
  • 20,821
  • 10
  • 70
  • 151
0

A command input is supposed to contain several parameters separated by spaces. For this reason, std::cin follows the same semantic and divide inputs by spaces.

WRITE YOUR INPUTS:
> hello world

Is considered by std::cin as 2 inputs.

input1: hello
input2: world

You may call std::cin several times to get them:

std::string str1, str2, str;
std::cin >> str1;
std::cin >> str2;
str = str1 + " " + str2;

Obviously and in most of the cases, we do not know how many words the user input, and calling std::cin several times make the program to block for a new input.

As an alternative, getline allows to get a single input:

std::string str;
std::getline(std::cin, str);
Adrian Maire
  • 14,354
  • 9
  • 45
  • 85