cin.getline is not working

Sep 12, 2010 at 6:33am
I am trying to do an assignment for class, but I cannot get this code to work. When I run it, it works fine up until it asks for the name of college...it skips where the user should input the name of a college and goes to the next question which is the "Name a profession". From there the rest work, but the final cout where I tell the story doesn't have anything for the variable college. I have looked at this site and many others, plus my book, and this is how they tell me to set it up. I am using Visual Studio 2010.Any ideas? Thanks in advance!!

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    char    name[21],
            city[31],
            profession[21],
            animal[21],
            college[31],
            petName[21];

    double    age;

    // Asking the questions
    cout << "What is your name?" << endl;
    cin >> name;
    cout << "What is your age (ie 19)?" << endl;
    cin >> age;
    cout << "The name of a city?" << endl;
    cin >> city;
    cout << "The name of a college?" << endl;
    cin.getline (college, 31);
    cout << "Name a profession." << endl;
    cin >> profession;
    cout << "What is a type of animal?" << endl;
    cin >> animal;
    cout << "What is a pet's name?" << endl;
    cin >> petName;

    //Display the results
    cout << "\nThere once was a person named " << name << " who lived in " << city << ". At the age of " << age << ", " << name << " went to college at ";
    cout << college << ". " << name << " graduated and went to work at a " << profession << ". Then, " << name << " adopted a(n) " << animal << " named ";
    cout << petName << ". They both lived happily ever after!\n";

    system("pause");
        
    return 0;

}   
Sep 12, 2010 at 7:11am
When you use cin>> to read data, you press enter to finish the response, but that enter ('\n') is left in the input buffer. So when you go to use cin.getline(), it sees that enter and reads it as you having pressed enter for that input.

You could use cin.ignore() to get rid of the newline.
Sep 12, 2010 at 2:24pm
It also seems kind of weird to simply assume the animal and name entered in was the person's pet. Maybe do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
string Pet("");

cout << "Do you have a pet? ";
cin.getline(cin, Pet, '\n');

if (Pet == 'yes' || Pet == 'Yes' || Pet == 'YES')
{
    cout << "What was your pet's name? ";
    cin >> petName;
    
    cout << "What kind of animal was it (species)? ";
    cin >> animal;

}


Etc. etc.
Sep 12, 2010 at 5:11pm
Thanks for the reply's I have tried what you said and I get errors when trying to compile. Again I am using Visual Studio 2010 with an "Empty Project". Not sure if that has anything to do with it...Below is my code.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    string  pet("");
    string    petName("");
    string    animal("");
    string    college("");

    char    name[21],
            city[31],
            profession[21],

    int        age;

    // Asking the questions
    cout << "What is your name?" << endl;
    cin >> name;
    cout << "What is your age (ie 19)?" << endl;
    cin >> age;
    cout << "The name of a city?" << endl;
    cin >> city;
    cout << "The name of a college?" << endl;
    cin.getline (cin, college, '\n');
    cout << "Name a profession." << endl;
    cin >> profession;
    cout << "Do you have a pet? ";
    cin.getline(cin, pet, '\n');
        if (pet == 'yes' || pet == 'Yes' || pet == 'YES')
        {
            cout << "What was your pet's name? ";
            cin >> petName;
    
            cout << "What kind of animal was it (species)? ";
            cin >> animal;

        }else
        {
            petName = 'Toby';
            animal = 'dog';
        }

    //Display the results
    cout << "\nThere once was a person named " << name << " who lived in " << city << ". At the age of " << age << ", " << name << " went to college at ";
    cout << college << ". " << name << " graduated and went to work at a " << profession << ". Then, " << name << " adopted a(n) " << animal << " named ";
    cout << petName << ". They both lived happily ever after!\n";

    system("pause");
        
    return 0;

}



Here is the error I get when I try to compile:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
1
1>Build started 9/12/2010 11:07:10 AM.
1>ClCompile:
1>  asg2d.cpp
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(23): error C2062: type 'int' unexpected
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(29): error C2065: 'age' : undeclared identifier
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(33): error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::getline(_Elem *,std::streamsize,_Elem)' : cannot convert parameter 1 from 'std::istream' to 'char *'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(37): error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::getline(_Elem *,std::streamsize,_Elem)' : cannot convert parameter 1 from 'std::istream' to 'char *'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(38): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(470): could be 'bool std::operator ==(const std::_Exception_ptr &,const std::_Exception_ptr &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(475): or       'bool std::operator ==(std::_Null_type,const std::_Exception_ptr &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(481): or       'bool std::operator ==(const std::_Exception_ptr &,std::_Null_type)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\system_error(408): or       'bool std::operator ==(const std::error_code &,const std::error_condition &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\system_error(416): or       'bool std::operator ==(const std::error_condition &,const std::error_code &)'
1>          while trying to match the argument list '(std::string, int)'
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(38): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(470): could be 'bool std::operator ==(const std::_Exception_ptr &,const std::_Exception_ptr &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(475): or       'bool std::operator ==(std::_Null_type,const std::_Exception_ptr &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(481): or       'bool std::operator ==(const std::_Exception_ptr &,std::_Null_type)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\system_error(408): or       'bool std::operator ==(const std::error_code &,const std::error_condition &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\system_error(416): or       'bool std::operator ==(const std::error_condition &,const std::error_code &)'
1>          while trying to match the argument list '(std::string, int)'
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(38): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(470): could be 'bool std::operator ==(const std::_Exception_ptr &,const std::_Exception_ptr &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(475): or       'bool std::operator ==(std::_Null_type,const std::_Exception_ptr &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\exception(481): or       'bool std::operator ==(const std::_Exception_ptr &,std::_Null_type)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\system_error(408): or       'bool std::operator ==(const std::error_code &,const std::error_condition &)'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\system_error(416): or       'bool std::operator ==(const std::error_condition &,const std::error_code &)'
1>          while trying to match the argument list '(std::string, int)'
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(48): warning C4305: 'argument' : truncation from 'int' to 'char'
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(48): warning C4309: 'argument' : truncation of constant value
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(49): warning C4305: 'argument' : truncation from 'int' to 'char'
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(49): warning C4309: 'argument' : truncation of constant value
1>c:\users\kraigballa\documents\visual studio 2010\projects\homework\asg2d\asg2d.cpp(53): error C2065: 'age' : undeclared identifier
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.83
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Sep 12, 2010 at 5:21pm
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    string  pet("");
    string  petName("");
    string  animal("");
    string  college("");

    char    name[21], city[31], profession[21]; //forgot your semicolon

    int     age;

    // Asking the questions
    cout << "What is your name?" << endl;
    cin >> name;
    cout << "What is your age (ie 19)?" << endl;
    cin >> age;
    cout << "The name of a city?" << endl;
    cin >> city;
    cout << "The name of a college?" << endl;
    getline (cin, college, '\n'); //not cin.getline()
    cout << "Name a profession." << endl;
    cin >> profession;
    cout << "Do you have a pet? ";
    getline(cin, pet, '\n'); //not cin.getline()
    if (pet == "yes" || pet == "Yes" || pet == "YES") //use double qoutes
    {
        cout << "What was your pet's name? ";
        cin >> petName;

        cout << "What kind of animal was it (species)? ";
        cin >> animal;

    }
    else
    {
        petName = "Toby"; //use double qoutes
        animal = "dog"; //use double qoutes
    }

    //Display the results
    cout << "\nThere once was a person named " << name << " who lived in " << city << ". At the age of " << age << ", " << name << " went to college at ";
    cout << college << ". " << name << " graduated and went to work at a " << profession << ". Then, " << name << " adopted a(n) " << animal << " named ";
    cout << petName << ". They both lived happily ever after!\n";


    return 0;

}
Sep 12, 2010 at 5:25pm
I corrected your syntax errors and made a few other notes:
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
	// No need to use constructor arguments
	// string pet("");
	// string petName("");
	// string animal("");
	// string college("");

	string pet;
	string petName;
	string animal;
	string college;

	// This is incorrect
	//    char    name[21],
	//            city[31],
	//            profession[21],

	char name[21];
	char city[31];
	char profession[21];
	int age;

	// Asking the questions
	cout << "What is your name?" << endl;
	cin >> name;
	cout << "What is your age (ie 19)?" << endl;
	cin >> age;
	cout << "The name of a city?" << endl;
	cin >> city;
	cout << "The name of a college?" << endl;

	// incorrect
	//	cin.getline(cin, college, '\n');
	getline(cin, college);

	cout << "Name a profession." << endl;
	cin >> profession;
	cout << "Do you have a pet? ";

	// incorrect
	//cin.getline(cin, pet, '\n');
	getline(cin, pet);

// Don't use single quotes for string literals, use double quotes
//	if(pet == 'yes' || pet == 'Yes' || pet == 'YES')
	if(pet == "yes" || pet == "Yes" || pet == "YES")
	{
		cout << "What was your pet's name? ";
		cin >> petName;

		cout << "What kind of animal was it (species)? ";
		cin >> animal;

	}
	else
	{
		petName = 'Toby';
		animal = 'dog';
	}

	//Display the results
	cout << "\nThere once was a person named " << name << " who lived in "
		<< city << ". At the age of " << age << ", " << name
		<< " went to college at ";
	cout << college << ". " << name << " graduated and went to work at a "
		<< profession << ". Then, " << name << " adopted a(n) " << animal
		<< " named ";
	cout << petName << ". They both lived happily ever after!\n";

	// try not to use system()
	//system("pause");
	cin.get();

	return 0;

}
Sep 12, 2010 at 5:52pm
I tried what blackcoder and galic said, and the compile errors are gone, but the program shows the cout for "The name of a college" and "Do you have a pet". However, it skips the cin part for both. So from the cout of "The name of a college" it goes right to "Name a profession". Then with the cout of "Do you have a pet" it goes directly to the results, which is the story.
Sep 12, 2010 at 6:04pm
Problem fixed!!! I added

cin.ignore(100,'\n');

before every getline syntax.
Sep 12, 2010 at 6:13pm
I tried what blackcoder and galic said, and the compile errors are gone
We intentionally did fixed only the syntax, not the program.

The point here is not to mixed operator >> with getline()
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

using namespace std;


//  this function is borrowed from the article section you shoud read it
//  http://cplusplus.com/articles/numb_to_text/
template <typename T>
  T StringToNumber ( const string &Text )
  {
     istringstream ss(Text);
     T result;
     return ss >> result ? result : 0;
  }


int main()
{
    string  pet, petName, animal, college, name, city, profession;
    string  tmpstr;
    int     age;

    cout << "What is your name?" << endl;
    getline(cin, name);

    cout << "What is your age (ie 19)?" << endl;
    getline(cin, tmpstr);
    age = StringToNumber<int>(tmpstr);

    cout << "The name of a city?" << endl;
    getline(cin, city);

    cout << "The name of a college?" << endl;
    getline (cin, college);

    cout << "Name a profession." << endl;
    getline (cin, profession);

    cout << "Do you have a pet? ";
    getline(cin, pet);

    if (pet == "yes" || pet == "Yes" || pet == "YES")
    {
        cout << "What was your pet's name? ";
        getline(cin, petName);

        cout << "What kind of animal was it (species)? ";
        getline(cin, animal);
    }
    else
    {
        petName = "Toby";
        animal = "dog";
    }

    cout << "\nThere once was a person named " << name << " who lived in " << city << ". At the age of " << age << ", " << name << " went to college at ";
    cout << college << ". " << name << " graduated and went to work at a " << profession << ". Then, " << name << " adopted a(n) " << animal << " named ";
    cout << petName << ". They both lived happily ever after!\n";


    return 0;
}

Notice the program only uses getline()

Here is a must read article..
http://cplusplus.com/articles/numb_to_text/
Topic archived. No new replies allowed.