My program by passes 'cin'

//i am stuck on something that i would think i should be able to figure, out but i cant

I am able to input the first part,mom's name, but the program bypasses the next input part and ends.

#include <iostream>
using namespace std;

int main()
{
char momname, dadname;

cout<<"Enter your mom's name:";
cin>>momname;

cout<<"\nEnter your dad's name:";
cin>>dadname;
return 0;
}


I have no idea what is going on
PLEase HELP ME



It could be picking up a stray null character. I had this problem in my classes last semester. Try cin.ignore() before cin >> dadname. This will toss the stray character and hopefully read in the actual data. :)
Last edited on
closed account (S6k9GNh0)
1. Don't shout.
2. Please, o please, use code tags from now on.
3. Fixed example and explanation:
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
#include <iostream>
#include <string>

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;
    using std::string;

    string momname, dadname;

    cout << "Enter your mom's name:";
    cin >> momname;
    cout << endl;

    cout << "\nEnter your dad's name:";
    cin >> dadname;
    cout << endl;

    cout << momname << endl;
    cout << dadname << endl;

    return 0;
}


In your example, momname and dadname are of type char, which represents one character. If you were to input one letter per name when it asked, this program would work. But if you were to input more than one letter, cin works like a queue and uses the first letter for momname and the second letter for dadname. In my example, I change the type from char to std::string which allows more than one character and dynamically allocates space for you as well. The C way, which we here at C++ do not recommend is to make an array of C characters like such:
char momname[30];
There isn't really anything wrong with this but it doesn't look very pretty and the question of how much should I allocate at first comes about where as std::string removes this all together.
The "Console Closing Down" thread stickied at the top of this board describes all about why this happens and the various ways to fix it.

I prefer the std::string class myself, using getline():
1
2
3
4
5
6
#include <iostream>
#include <string>

string str;
getline(cin, str);
cout << str;


hth
Thank you to all.
My Problem is fixed.
Topic archived. No new replies allowed.