Why can't I input anything?

Apr 20, 2015 at 10:43pm
Whenever I run the program a number is automatically input and i just get this,
1 What is your name?
2 Hello � !

Code
#include <iostream>
using namespace std;

int main()
{
char name;
cout << "What is your name? \n";
cin>> name;
cout << "Hello " << name;
cout << " !";
return 0;
}
Last edited on Apr 20, 2015 at 10:43pm
Apr 20, 2015 at 10:52pm
Please remember to put your code between the source code brackets so it can be read easily.


Your code is doing exactly what you wrote it to do: print one letter. A char is a single character. If you want to print out an entire word, you need a char array.

But even then, it will only output the first name (if both first and last names are written) because a space stops the input. If you want both names to be printed, use the getline function.
Last edited on Apr 20, 2015 at 10:53pm
Apr 21, 2015 at 12:32pm
If you want to print out an entire word, you need a char array.


Nope. You Need a string, don't use char arrays.

1
2
3
4
5
6
7
8
9
int main()
{
string name;
cout << "What is your name? \n";
cin>> name;
cout << "Hello " << name;
cout << " !";
return 0;
}
Apr 21, 2015 at 1:22pm
Yes, I suppose you can also use a string.
Apr 21, 2015 at 1:23pm
Yes, I suppose you can also use a string.


Should, not could. Should use string. You can use char array if you program in C. Dont do it in c++.
Apr 22, 2015 at 4:07am
Can you explain why though? Is there a specific benefit of string over char array in this case?
Last edited on Apr 22, 2015 at 4:08am
Topic archived. No new replies allowed.