i'm having problems

I'm pretty new at this c++ langauge and I don't know why my code does this. When the console asks you your name and you just put in one word, the program seems to work fine. But if you put in two or more words, it seems to skip the other questions and use the second word for the answer to the next question. Does anybody know how to fix this problem?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	char name[10];
	cout<<"What is your name?  ";
	cin>>name;
	cout<<"Well, nice to meet you "<<name<<"! My name is not important right now."<<endl;
	cout<<"How are you?   ";
	cin>>name;
	cout<<"O really now? you are doing "<<name<<"? I don't really care how you are doing."<<endl;
	cout<<"What? Are you mad now?  ";
	cin>>name;
	cout<<"I don't care if you are or not."<<endl;
	cout<<"How old are you?   ";
	cin>>name;
	cout<<"You are way to old for me. I'm not even one day old yet."<<endl;
	cout<<"Conversational Partner Disconnected"<<endl;
	system("pause");
	return 0;
}
Recommendation: use std::string and getline. When you use cin >> name, it reads until it finds a whitespace (i.o.w. one word), however it doesn't clear cin's buffer. When you use cin >> name the next time, it doesn't need to wait for the user to input a word because there already is one in the buffer, so it uses that instead. With getline(), it reads in the entire line.

string name; //Replaces the char name[10]; line, lets your strings be indefinitely long.

getline(cin,name); //Replaces the cins, fixes the word-still-in-buffer issue.

cin.ignore() //Replaces system("pause"), fixes all the issues caused by system().

Have fun!

-Albatross
Last edited on
may be you should use
getline(cin, name)
http://cplusplus.com/doc/tutorial/basic_io/
Last edited on
If you're expecting input with spaces, you should use cin.getline(). It is used like this:
cin.getline(variable, max_chars);
You might want name to hold more than 10 chars too.

Edit: A bit slow, oh well.
Last edited on
thank you. The problem was fixed and my program works perfectly. =] Now all i have to do is learn the rest of the langauge......
Topic archived. No new replies allowed.