-
Extremely basic question
Code:
#include <iostream>
using namespace std;
int main()
{
int age;
char name[8];
cout<<"How old are you?";
cin>>age;
cout<<"\nAnd what is your name?";
cin>>name;
cout<<"\nSo you're " << name << " and you are " << age << "years old.";
return 0;
}
Uhh...whenever I run the progra it never shows the last line cout<<"\nSo you're " << name << " and you are " << age << "years old.";. It just asks me what my name is and once i hit type in my name and hit enter, it closes. I know this is extremely basic, but I just want to make sure I am very comfortable with the basics. Anyone know why this is happening?
-
I bet it shows it, but then immediately closes the window, so you do not have enough time to see it. See the FAQ for a few examples of "How do I stop the window from disappearing when I run my program".
--
Mats
-
Hmm I used to the example the FAQ gave,
Code:
#include <iostream>
using namespace std;
void mypause()
{
cout<<"Press [Enter] to continue...";
cin.get();
}
int main()
{
int age;
char name[8];
cout<<"How old are you?";
cin>>age;
cout<<"\nAnd what is your name?";
cin>>name;
cout<<"\nSo you're " << name << " and you are " << age << "years old.";
mypause();
return 0;
}
and it still does not wait for a keypress. I know I can go to the command line, but I would rather learn how to code better than use the computer better. Is there anything I could do different? I use the Dev-C++ compiler if that helps
-
try this
Code:
#include <iostream>
using namespace std;
int main()
{
int age;
char name[8];
cout<<"How old are you?";
cin>>age;
cout<<"\nAnd what is your name?";
cin>>name;
cout<<"\nSo you're " << name << " and you are " << age << "years old.";
system("pause"); //it pauses it so you can see it
return 0;
}
-
-
chances are, you're entering your full name (with a space in between first and last). cin sees a space as an input delimiter, and leaves the last name in the input buffer for the next call to cin>>. when it calls cin>> the next time, it finds the data that's still in the input buffer and tries to convert it to an int, which it can't, so it's possible that it's actually terminating due to an internal error. try the following:
Code:
cout << "enter your name: ";
cin >> name;
cin.ignore();
cout << "enter your age: ";
cin >> age;
cin.ignore();
it should get you close to your desired result. cin.ignore() throws away whatever is left in the buffer after putting what it thinks you want into your char array.
another possibility is the following:
Code:
int age;
string name;
cout << "enter your name: ";
getline(cin, name);
cin.ignore();
cout << "enter your age: ";
cin >> age;
cin.ignore;
this will read as much input as you provide until it reaches a newline character (carriage return) and will store the result into the string.