cin and cout are different

Sep 9, 2009 at 11:46pm
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.
Sep 10, 2009 at 12:06am
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.
Sep 10, 2009 at 12:08am
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 Sep 10, 2009 at 12:08am
Sep 10, 2009 at 12:14am
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.
Sep 10, 2009 at 1:37am
...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);
Sep 10, 2009 at 9:54am
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..
Sep 10, 2009 at 10:27am
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.