-4

The code is not giving desired output when I type in a string example "Ben Parker", the output is "Goodmorning, Ben" and not the entire name("Ben Parker") what seems to be the problem?

#include <iostream>
#include <stdlib.h> 
#include <cstring>

int main() {
char your_name[20];

std::cout << "Enter your name: ";
std::cin >> your_name;
std::cout << "Goodmorning, ";
std::cout.write (your_name, strlen(your_name)) << std::endl;

return 0;
}

SOLUTION

This was a very old question when I just began programming. The entire character array can be read and printed with a for loop, or better a string type variable can be used, since it is C++.

using string your_name; seems to fix the problem, which can be then printed with a simple std::cout << your_name << endl;

Cœur
  • 37,241
  • 25
  • 195
  • 267
Archetype2142
  • 190
  • 3
  • 14

1 Answers1

3

You probably put a space in between "Ben" and "Parker" in input. This would cause the cin logic to believe it had an answer after seeing the space following "Ben". You will probably want to read an entire line at a time to get past that problem. See this page for an example.

Logicrat
  • 4,438
  • 16
  • 22