cin and cout are different

anyone have any idea whey when i use
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int name;
cout << "type your name" << endl;
cin >> name;
cout << "your name is " << name << endl;
system("PAUSE");
return EXIT_SUCCESS;
}

everytime i type a name in it output a number a large number.
I using vista x64 home premium and I tried on visual studio and dev c++ both give me large number instead of what i input in. Console window.
When the user input can't be converted to the type of the variable, std::cin >> leaves the variable's value untouched. You're seeing what the variable looks like uninitialized.
'name' is an int, which can only hold a positive or negative number, not a name or any other string.
Notice what you are trying to store your name in.

That variable holds numbers not strings of letters.

Change your code to this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
  string name;

  cout << "Type your name: ";
  cin >> name; // note: it's best to use getline(cin, STRING NAME); to read strings in

  cout << "Your name is " << name << endl;

  system("pause");

  return 0;
}

Last edited on
Your variable "name" is an integer and when you type your name in, it will convert the first letter you typed into a character code, store the rest in an input buffer, and cout will print out the number.
...change the int name; to string name;
if you want to include spaces then use this

1
2
3
4
5
6
 
string name;
....................
.....................
cout << "enter your name: ";
getline(cin, name);
you cannot convert an int to a string type ..
int is used for integers values and may not accept any words and letters...
so for displaying names use char data type instead of int..
I don't think there needs to be 5 (6 now) different posts telling him that he's using an integer instead of an array of characters.
Topic archived. No new replies allowed.