-1

I am trying to write a simple program that reads a name as a C-style string. The name is then printed vertically, one character per line.

Currently when the program prompts a user to enter their name, eg. Henry James, only 'Henry' is printed vertically. It stops printing at the break between the names.

char myName[ 64 ] = "";
cout << "Enter your name: ";
cin.get( myName, 64 );

int i = 0;
while ( myName [ i ] != ' ' )
    {
        cout << myName[ i ] << endl;
        i++;
    }



getch();
return 0;

I've tried putting cin.ignore() the line before cin.get(), but this ends up breaking the program. What am I missing in the while loop?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Dinomo
  • 11
  • 1
  • 10
    You explicitly write that your loop should stop at ' ' space character. Everything as expected :-) – Klaus Aug 08 '19 at 09:35
  • If you're entering multiple words per line and you want them *all* in a single string, use `std::getline` . It's literally what the function was made for. – WhozCraig Aug 08 '19 at 09:36
  • Ha! Silly mistake, thank you :) – Dinomo Aug 08 '19 at 09:39

1 Answers1

6

You explicitly write that your loop should stop at ' ' space character. Everything as expected :-)

If you want to print until end of the C style string, check against the terminating char which is a zero.

while ( myName [ i ] != '\0' )
Klaus
  • 24,205
  • 7
  • 58
  • 113