1

I'm new here so please excuse if I didn't explain the question well or something. This is my code, and I'm trying to get user input. The thing is I want to print out what the user says even if they include spacing. However, I'm stuck. This is my code... any ideas? Thank you in advance!

#include <iostream>
#include <string>

int main() {
    char name[200];
    std::cout << "What is your name? ";
    std::getline( std::cin, name );
    std::cout << "Welcome to CS adventures, " << name <<"!";
}
einpoklum
  • 118,144
  • 57
  • 340
  • 684

4 Answers4

4

std::getline requires a std::string, not a character array.

char name[200];

should become

std::string name;

but student programmers seem to have been made to suffer because instructors tend to have a "No strings" rule. You may need to use std::istream::getline because it will accept a character array. In this case

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

needs to become

std::cin.getline( name, sizeof(name) );
user4581301
  • 33,082
  • 7
  • 33
  • 54
2

Actually, your code doesn't compile. std::getline expects an std::string, not a char *.

The following code works just fine:

int main()
{
    std::string line;
    std::cout << "What is your name? ";
    std::getline( std::cin, line );
    std::cout << "Welcome to CS adventures, " << line <<"!";
}
Daniel Trugman
  • 8,186
  • 20
  • 41
0

You have to use getline as follows std::cin.getline(name,sizeof(name)); See this post

madvn
  • 33
  • 7
0

You should use string type for name variable. "Getline(string)" method only works with string parameter. Here's example :

#include <iostream>
#include <string>

    int main ()
    {
      std::string name;
    
      std::cout << "Please, enter your full name: ";
      std::getline (std::cin,name);
      std::cout << "Hello, " << name << "!\n";
    
      return 0;
    }