getline

Hello guys, im trying to figure out whats wrong with this code, I am also not sure in how to use the getline part, if anyone can help me it would be great. thank you so much


#include <iostream>;
using namespace std;
int main()
{
char name, go;
cout << "Enter your name: ";
getline >> name;
cout << "Hi " << name << endl;
return 0;
}
Hello andreswp10,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

First off "name" and "go" are defined as a "char", so it will only hold one character. What you need to do is include the header file <string> then use std::string name{}, go{};. The empty {} will initialize the variables to empty strings.

Then the proper use for "getline" is std::getline(std::cin, name);.

Hope that helps,

Andy
You may not actually need getline to begin with.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Hi " << name << endl;
} 


That's ok for names without any spaces - just a single word. If you want to include spaces, then:
 
    cin >> name;
becomes
 
    getline(cin, name);


See tutorial:
http://www.cplusplus.com/doc/tutorial/basic_io/
What you need to do is include the header file <string> then use std::string name{}, go{};. The empty {} will initialize the variables to empty strings.


Those empty braces {} are redundant here. A std::string is default initialised to an empty string with no further action required.

Just put std::string name; or simply string name; if you have the 'using namespace std;' declaration.
Topic archived. No new replies allowed.