Practice

Can someone provide me a solution to this program without using cin.ignore?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>

using namespace std;

int main (){
    int myFaveNumber;
    string faveClass;
    
    cout << "What is your favorite number? (integers only, please): ";
    cin >> myFaveNumber;
    cout << "What is your favorite class?";
    getline (cin, faveClass);
    
    cout << "\nMy favorite class is " << faveClass << ", and my favorite number is "
         << myFaveNumber << ".\n";
    
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

using namespace std;

int main (){
    int myFaveNumber;
    string faveClass;
    
    cout << "What is your favorite number? (integers only, please): ";
    cin >> myFaveNumber;
    cout << "What is your favorite class?";
    cin>>faveClass;
    
    cout << "\nMy favorite class is " << faveClass << ", and my favorite number is "
         << myFaveNumber << ".\n";
    
    return 0;
}
Last edited on
What's wrong with using ignore()? Sometimes that is the best way of proceeding.

If your problem is the skipping of the getline() then you could try:

getline (cin >> ws, faveClass);
However this won't solve any problem other than skipping leading whitespace, if you enter an incorrect entry for myFaveNumber you will still skip any other entries.
That does not work because I am unable to get the full string.
Well for our practice, we are supposed to find a clever way to get the correct output with out using cin.ignore
> I am unable to get the full string.

To read a complete line, use std::getline() http://www.cplusplus.com/reference/string/string/getline/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <iomanip>

int main () {

    std::cout << "What is your favourite number? (integers only, please): ";
    int myFaveNumber;

    if( std::cin >> myFaveNumber ) {

        std::cout << "What is your favourite class? ";
        std::string faveClass;

        // http://www.cplusplus.com/reference/string/string/getline/
        std::getline( std::cin >> std::ws, faveClass ) ;

        std::cout << "\nMy favourite class is " << std::quoted(faveClass)
                  << ", and my favourite number is " << myFaveNumber << ".\n";
    }
}
Thank you guys. I figured it out.
monrelle you can just put first the question of getting favorite class and the second question will be the favorite number. You will not now worry of using cin.ignore.

1
2
3
4
cout << "What is your favorite class?";
    cin>>faveClass;
cout << "What is your favorite number? (integers only, please): ";
    cin >> myFaveNumber;
Last edited on
Topic archived. No new replies allowed.