-2

I couldn't figure out how to have an input with spaces stored in a string so I store it in a char first and I want to copy it to the string.

string name[2]={"Sample name"};
char apname[50];

cout << "Input Name: ";
cin.getline(apname,sizeof(apname));
strcpy (apname,name[2]);

If there's an easier way to do this please help me.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
Harri Caceres
  • 79
  • 3
  • 8

2 Answers2

1

This is the better way:

std::string line;
std::getline(std::cin, line);
std::cout << "You said: " << line << "\n";

With error checking, prompting, and repetition, it'd be:

for (std::string line;
     (std::cout << "Input name: ") && std::getline(std::cin, line); )
{
    std::cout << "You said: " << line << "\n";
}
std::cout << "Goodbye\n";
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

In addition to operator << which skips whitespace C++ Standard Library provides std::getline function overload for strings. Use it instead:

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

Your function that calls

strcpy(apname, name[2]);

is incorrect for several reasons:

  • You cannot copy characters directly into a string
  • name[2] on an array of two items is referencing an item past the end of the array.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523