If statements in a do while loop with a yes or no ending

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
13
down vote

favorite












I am new to coding and I'm trying to do a long do while loop with nested if statements but I'm having issues with getting my loop to actually loop.



Instead of getting help directly on my project, which has a very long code, I made a simple kind of like it version. It also does not loop. It will get to the end and ask the user if they want to try again but when "y" is entered it ignores the if statements.



#include <iostream>
#include <string>
using namespace std;

int main()

string sodaChoice;
char answer = 'n';

do

cout << "Please choose your favorite soda from the following: Rootbeer, Diet Coke, Coke, Sprite" << "n";
getline(cin, sodaChoice);

if (sodaChoice == "Rootbeer")

cout << "Me too!" << "n";

else if (sodaChoice == "Diet")

cout << "Not me :(" << "n";

else if (sodaChoice == "Coke")

cout << "It's alright" << "n";

else if (sodaChoice == "Sprite")

cout << "only if I'm sick" << "n";


else

cout << "That was not on the list";

cout << "would you like to try again?";
cin >> answer;



while (answer == 'y'


I thought maybe I needed a do loop in the do loop around the if statements but then I didn't know how to go about it. Any help would be appreciated. I have spent many, many hours trying to figure it out.



I tried to ask my teacher, but my college teaches from some generic curriculum that their dean wrote based on her book. He is not very enthusiastic about helping or teaching.










share|improve this question









New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3




    Although please remove the second, off-topic question :P
    – Lightness Races in Orbit
    7 hours ago










  • I have no idea what's happening, but it works perfectly for me. Besides,
    – user202729
    7 mins ago










  • std::cin ignores spaces by default.
    – user202729
    5 mins ago














up vote
13
down vote

favorite












I am new to coding and I'm trying to do a long do while loop with nested if statements but I'm having issues with getting my loop to actually loop.



Instead of getting help directly on my project, which has a very long code, I made a simple kind of like it version. It also does not loop. It will get to the end and ask the user if they want to try again but when "y" is entered it ignores the if statements.



#include <iostream>
#include <string>
using namespace std;

int main()

string sodaChoice;
char answer = 'n';

do

cout << "Please choose your favorite soda from the following: Rootbeer, Diet Coke, Coke, Sprite" << "n";
getline(cin, sodaChoice);

if (sodaChoice == "Rootbeer")

cout << "Me too!" << "n";

else if (sodaChoice == "Diet")

cout << "Not me :(" << "n";

else if (sodaChoice == "Coke")

cout << "It's alright" << "n";

else if (sodaChoice == "Sprite")

cout << "only if I'm sick" << "n";


else

cout << "That was not on the list";

cout << "would you like to try again?";
cin >> answer;



while (answer == 'y'


I thought maybe I needed a do loop in the do loop around the if statements but then I didn't know how to go about it. Any help would be appreciated. I have spent many, many hours trying to figure it out.



I tried to ask my teacher, but my college teaches from some generic curriculum that their dean wrote based on her book. He is not very enthusiastic about helping or teaching.










share|improve this question









New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3




    Although please remove the second, off-topic question :P
    – Lightness Races in Orbit
    7 hours ago










  • I have no idea what's happening, but it works perfectly for me. Besides,
    – user202729
    7 mins ago










  • std::cin ignores spaces by default.
    – user202729
    5 mins ago












up vote
13
down vote

favorite









up vote
13
down vote

favorite











I am new to coding and I'm trying to do a long do while loop with nested if statements but I'm having issues with getting my loop to actually loop.



Instead of getting help directly on my project, which has a very long code, I made a simple kind of like it version. It also does not loop. It will get to the end and ask the user if they want to try again but when "y" is entered it ignores the if statements.



#include <iostream>
#include <string>
using namespace std;

int main()

string sodaChoice;
char answer = 'n';

do

cout << "Please choose your favorite soda from the following: Rootbeer, Diet Coke, Coke, Sprite" << "n";
getline(cin, sodaChoice);

if (sodaChoice == "Rootbeer")

cout << "Me too!" << "n";

else if (sodaChoice == "Diet")

cout << "Not me :(" << "n";

else if (sodaChoice == "Coke")

cout << "It's alright" << "n";

else if (sodaChoice == "Sprite")

cout << "only if I'm sick" << "n";


else

cout << "That was not on the list";

cout << "would you like to try again?";
cin >> answer;



while (answer == 'y'


I thought maybe I needed a do loop in the do loop around the if statements but then I didn't know how to go about it. Any help would be appreciated. I have spent many, many hours trying to figure it out.



I tried to ask my teacher, but my college teaches from some generic curriculum that their dean wrote based on her book. He is not very enthusiastic about helping or teaching.










share|improve this question









New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I am new to coding and I'm trying to do a long do while loop with nested if statements but I'm having issues with getting my loop to actually loop.



Instead of getting help directly on my project, which has a very long code, I made a simple kind of like it version. It also does not loop. It will get to the end and ask the user if they want to try again but when "y" is entered it ignores the if statements.



#include <iostream>
#include <string>
using namespace std;

int main()

string sodaChoice;
char answer = 'n';

do

cout << "Please choose your favorite soda from the following: Rootbeer, Diet Coke, Coke, Sprite" << "n";
getline(cin, sodaChoice);

if (sodaChoice == "Rootbeer")

cout << "Me too!" << "n";

else if (sodaChoice == "Diet")

cout << "Not me :(" << "n";

else if (sodaChoice == "Coke")

cout << "It's alright" << "n";

else if (sodaChoice == "Sprite")

cout << "only if I'm sick" << "n";


else

cout << "That was not on the list";

cout << "would you like to try again?";
cin >> answer;



while (answer == 'y'


I thought maybe I needed a do loop in the do loop around the if statements but then I didn't know how to go about it. Any help would be appreciated. I have spent many, many hours trying to figure it out.



I tried to ask my teacher, but my college teaches from some generic curriculum that their dean wrote based on her book. He is not very enthusiastic about helping or teaching.







c++ if-statement do-while






share|improve this question









New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 8 mins ago









svick

167k39283400




167k39283400






New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 7 hours ago









JKisa

694




694




New contributor




JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






JKisa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 3




    Although please remove the second, off-topic question :P
    – Lightness Races in Orbit
    7 hours ago










  • I have no idea what's happening, but it works perfectly for me. Besides,
    – user202729
    7 mins ago










  • std::cin ignores spaces by default.
    – user202729
    5 mins ago












  • 3




    Although please remove the second, off-topic question :P
    – Lightness Races in Orbit
    7 hours ago










  • I have no idea what's happening, but it works perfectly for me. Besides,
    – user202729
    7 mins ago










  • std::cin ignores spaces by default.
    – user202729
    5 mins ago







3




3




Although please remove the second, off-topic question :P
– Lightness Races in Orbit
7 hours ago




Although please remove the second, off-topic question :P
– Lightness Races in Orbit
7 hours ago












I have no idea what's happening, but it works perfectly for me. Besides,
– user202729
7 mins ago




I have no idea what's happening, but it works perfectly for me. Besides,
– user202729
7 mins ago












std::cin ignores spaces by default.
– user202729
5 mins ago




std::cin ignores spaces by default.
– user202729
5 mins ago












4 Answers
4






active

oldest

votes

















up vote
11
down vote













With



cin >> answer;


you read exactly one character. The problem is that you entered at least two characters when writing the answer. The actual 'y' or 'n' plus the Enter key, which is added as a newline in the input buffer.



This newline is then read by the next getline call as an empty line.



There are a few solutions to this problem, for example using ignore after reading into answer. Or if you want only one-word inputs then you could use formatted input using >> for sodaChoice too, since it will by default skip leading white-space (like newlines).






share|improve this answer






















  • I don't think so, stackoverflow.com/questions/52717083/…
    – user202729
    4 mins ago

















up vote
5
down vote













Existing answers are correct in the case of the user behaving nicely and entering just a 'y' or an 'n' followed by a newline.



We can add a little safety with a modification to the .ignore() call by asking it to ignore all characters up to an including the next newline:



You will need to add this header include at the top of your translation unit:



#include <limits>


And you'll need to add this line before cin >> answer:



// consumes and ignores as many characters as necessary until a newline. 
// The newline is also consumed.
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');


Full program with test inputs here:



http://coliru.stacked-crooked.com/a/996e77559590ad6d



Unfortunately, it's not unusual for Computer Science teachers to know nothing about computer science. Don't worry about this or let it put you off learning how to write software - it's just a symptom of the fact that good software engineers get paid a lot more than good teachers.



Here is some useful reference material: https://en.cppreference.com/w/cpp/io/basic_istream/ignore






share|improve this answer



























    up vote
    3
    down vote













    I'm going to suggest something entirely the opposite of the other answers. Instead of using cin.ignore to skip any extra characters after the one you read, I think it's better to do all your reading with getline() and forget about cin >> somevar completely.



    There are two reasons:



    1. The formatted input you get with cin >> somevar ignores leading whitespace, including newlines. If the user hits Enter on an empty line the program doesn't do anything, but still expects further input. This is not what the user of a CLI program expects! The usual expectation is that Enter completes the input, and an empty input should either cause the program to use a default value, or to complain about invalid input. With cin >> somevar, you can't do either.



    2. Formatted input leaves any unmatched input in the buffer. In your example, reading a single character leaves at least the following newline, but the same happens with other kinds of input. Reading a number (with int i; cin >> i;) leaves anything after the number waiting for the next input operation, so entering 123 abc will return 123, and the abc will appear on the next input operation.



      The underlying cause of this is that by default, a command-line terminal is in a line-based mode. The program or the library functions don't see any input from the operating system until a complete line is entered. (cin.ignore() can of course help you deal with this, but not with the first point.)



    Using getline() matches the underlying mechanic exactly, lets you deal with empty inputs (as well as telling the difference between a zero, and a non-number when reading to an int), and automatically deals with the trailing garbage. You'll have to convert the read string manually to whatever it is you actually want, though.



    In your case, you could change the loop condition trivially to something like this:



    string answer;
    ...
    getline(cin, answer);
    } while (answer == "y" || answer == "Y");


    If you need a number, you can use e.g. int num = std::stoi(str).




    (In C, the same happens if using scanf() for user input, and similarly, it's better to use fgets() and then parse the string with sscanf(), which gives the same options but deals with line-buffering. I'm not too familiar with C++, so I can't tell how to have the exact equivalent of cin >> somevar with a full line read by getline().)






    share|improve this answer



























      up vote
      0
      down vote













      Since you are taking input from the user of type char but every Enter key hit, it assigns the newline (n) to the variable answer.



      You can ignore this by adding a line just after the input line



      cin.ignore();


      You may read this for more details.






      share|improve this answer




















        Your Answer





        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: false,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );






        JKisa is a new contributor. Be nice, and check out our Code of Conduct.









         

        draft saved


        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52717083%2fif-statements-in-a-do-while-loop-with-a-yes-or-no-ending%23new-answer', 'question_page');

        );

        Post as a guest






























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        11
        down vote













        With



        cin >> answer;


        you read exactly one character. The problem is that you entered at least two characters when writing the answer. The actual 'y' or 'n' plus the Enter key, which is added as a newline in the input buffer.



        This newline is then read by the next getline call as an empty line.



        There are a few solutions to this problem, for example using ignore after reading into answer. Or if you want only one-word inputs then you could use formatted input using >> for sodaChoice too, since it will by default skip leading white-space (like newlines).






        share|improve this answer






















        • I don't think so, stackoverflow.com/questions/52717083/…
          – user202729
          4 mins ago














        up vote
        11
        down vote













        With



        cin >> answer;


        you read exactly one character. The problem is that you entered at least two characters when writing the answer. The actual 'y' or 'n' plus the Enter key, which is added as a newline in the input buffer.



        This newline is then read by the next getline call as an empty line.



        There are a few solutions to this problem, for example using ignore after reading into answer. Or if you want only one-word inputs then you could use formatted input using >> for sodaChoice too, since it will by default skip leading white-space (like newlines).






        share|improve this answer






















        • I don't think so, stackoverflow.com/questions/52717083/…
          – user202729
          4 mins ago












        up vote
        11
        down vote










        up vote
        11
        down vote









        With



        cin >> answer;


        you read exactly one character. The problem is that you entered at least two characters when writing the answer. The actual 'y' or 'n' plus the Enter key, which is added as a newline in the input buffer.



        This newline is then read by the next getline call as an empty line.



        There are a few solutions to this problem, for example using ignore after reading into answer. Or if you want only one-word inputs then you could use formatted input using >> for sodaChoice too, since it will by default skip leading white-space (like newlines).






        share|improve this answer














        With



        cin >> answer;


        you read exactly one character. The problem is that you entered at least two characters when writing the answer. The actual 'y' or 'n' plus the Enter key, which is added as a newline in the input buffer.



        This newline is then read by the next getline call as an empty line.



        There are a few solutions to this problem, for example using ignore after reading into answer. Or if you want only one-word inputs then you could use formatted input using >> for sodaChoice too, since it will by default skip leading white-space (like newlines).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 7 hours ago

























        answered 7 hours ago









        Some programmer dude

        285k24233392




        285k24233392











        • I don't think so, stackoverflow.com/questions/52717083/…
          – user202729
          4 mins ago
















        • I don't think so, stackoverflow.com/questions/52717083/…
          – user202729
          4 mins ago















        I don't think so, stackoverflow.com/questions/52717083/…
        – user202729
        4 mins ago




        I don't think so, stackoverflow.com/questions/52717083/…
        – user202729
        4 mins ago












        up vote
        5
        down vote













        Existing answers are correct in the case of the user behaving nicely and entering just a 'y' or an 'n' followed by a newline.



        We can add a little safety with a modification to the .ignore() call by asking it to ignore all characters up to an including the next newline:



        You will need to add this header include at the top of your translation unit:



        #include <limits>


        And you'll need to add this line before cin >> answer:



        // consumes and ignores as many characters as necessary until a newline. 
        // The newline is also consumed.
        cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');


        Full program with test inputs here:



        http://coliru.stacked-crooked.com/a/996e77559590ad6d



        Unfortunately, it's not unusual for Computer Science teachers to know nothing about computer science. Don't worry about this or let it put you off learning how to write software - it's just a symptom of the fact that good software engineers get paid a lot more than good teachers.



        Here is some useful reference material: https://en.cppreference.com/w/cpp/io/basic_istream/ignore






        share|improve this answer
























          up vote
          5
          down vote













          Existing answers are correct in the case of the user behaving nicely and entering just a 'y' or an 'n' followed by a newline.



          We can add a little safety with a modification to the .ignore() call by asking it to ignore all characters up to an including the next newline:



          You will need to add this header include at the top of your translation unit:



          #include <limits>


          And you'll need to add this line before cin >> answer:



          // consumes and ignores as many characters as necessary until a newline. 
          // The newline is also consumed.
          cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');


          Full program with test inputs here:



          http://coliru.stacked-crooked.com/a/996e77559590ad6d



          Unfortunately, it's not unusual for Computer Science teachers to know nothing about computer science. Don't worry about this or let it put you off learning how to write software - it's just a symptom of the fact that good software engineers get paid a lot more than good teachers.



          Here is some useful reference material: https://en.cppreference.com/w/cpp/io/basic_istream/ignore






          share|improve this answer






















            up vote
            5
            down vote










            up vote
            5
            down vote









            Existing answers are correct in the case of the user behaving nicely and entering just a 'y' or an 'n' followed by a newline.



            We can add a little safety with a modification to the .ignore() call by asking it to ignore all characters up to an including the next newline:



            You will need to add this header include at the top of your translation unit:



            #include <limits>


            And you'll need to add this line before cin >> answer:



            // consumes and ignores as many characters as necessary until a newline. 
            // The newline is also consumed.
            cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');


            Full program with test inputs here:



            http://coliru.stacked-crooked.com/a/996e77559590ad6d



            Unfortunately, it's not unusual for Computer Science teachers to know nothing about computer science. Don't worry about this or let it put you off learning how to write software - it's just a symptom of the fact that good software engineers get paid a lot more than good teachers.



            Here is some useful reference material: https://en.cppreference.com/w/cpp/io/basic_istream/ignore






            share|improve this answer












            Existing answers are correct in the case of the user behaving nicely and entering just a 'y' or an 'n' followed by a newline.



            We can add a little safety with a modification to the .ignore() call by asking it to ignore all characters up to an including the next newline:



            You will need to add this header include at the top of your translation unit:



            #include <limits>


            And you'll need to add this line before cin >> answer:



            // consumes and ignores as many characters as necessary until a newline. 
            // The newline is also consumed.
            cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');


            Full program with test inputs here:



            http://coliru.stacked-crooked.com/a/996e77559590ad6d



            Unfortunately, it's not unusual for Computer Science teachers to know nothing about computer science. Don't worry about this or let it put you off learning how to write software - it's just a symptom of the fact that good software engineers get paid a lot more than good teachers.



            Here is some useful reference material: https://en.cppreference.com/w/cpp/io/basic_istream/ignore







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 7 hours ago









            Richard Hodges

            54.6k55698




            54.6k55698




















                up vote
                3
                down vote













                I'm going to suggest something entirely the opposite of the other answers. Instead of using cin.ignore to skip any extra characters after the one you read, I think it's better to do all your reading with getline() and forget about cin >> somevar completely.



                There are two reasons:



                1. The formatted input you get with cin >> somevar ignores leading whitespace, including newlines. If the user hits Enter on an empty line the program doesn't do anything, but still expects further input. This is not what the user of a CLI program expects! The usual expectation is that Enter completes the input, and an empty input should either cause the program to use a default value, or to complain about invalid input. With cin >> somevar, you can't do either.



                2. Formatted input leaves any unmatched input in the buffer. In your example, reading a single character leaves at least the following newline, but the same happens with other kinds of input. Reading a number (with int i; cin >> i;) leaves anything after the number waiting for the next input operation, so entering 123 abc will return 123, and the abc will appear on the next input operation.



                  The underlying cause of this is that by default, a command-line terminal is in a line-based mode. The program or the library functions don't see any input from the operating system until a complete line is entered. (cin.ignore() can of course help you deal with this, but not with the first point.)



                Using getline() matches the underlying mechanic exactly, lets you deal with empty inputs (as well as telling the difference between a zero, and a non-number when reading to an int), and automatically deals with the trailing garbage. You'll have to convert the read string manually to whatever it is you actually want, though.



                In your case, you could change the loop condition trivially to something like this:



                string answer;
                ...
                getline(cin, answer);
                } while (answer == "y" || answer == "Y");


                If you need a number, you can use e.g. int num = std::stoi(str).




                (In C, the same happens if using scanf() for user input, and similarly, it's better to use fgets() and then parse the string with sscanf(), which gives the same options but deals with line-buffering. I'm not too familiar with C++, so I can't tell how to have the exact equivalent of cin >> somevar with a full line read by getline().)






                share|improve this answer
























                  up vote
                  3
                  down vote













                  I'm going to suggest something entirely the opposite of the other answers. Instead of using cin.ignore to skip any extra characters after the one you read, I think it's better to do all your reading with getline() and forget about cin >> somevar completely.



                  There are two reasons:



                  1. The formatted input you get with cin >> somevar ignores leading whitespace, including newlines. If the user hits Enter on an empty line the program doesn't do anything, but still expects further input. This is not what the user of a CLI program expects! The usual expectation is that Enter completes the input, and an empty input should either cause the program to use a default value, or to complain about invalid input. With cin >> somevar, you can't do either.



                  2. Formatted input leaves any unmatched input in the buffer. In your example, reading a single character leaves at least the following newline, but the same happens with other kinds of input. Reading a number (with int i; cin >> i;) leaves anything after the number waiting for the next input operation, so entering 123 abc will return 123, and the abc will appear on the next input operation.



                    The underlying cause of this is that by default, a command-line terminal is in a line-based mode. The program or the library functions don't see any input from the operating system until a complete line is entered. (cin.ignore() can of course help you deal with this, but not with the first point.)



                  Using getline() matches the underlying mechanic exactly, lets you deal with empty inputs (as well as telling the difference between a zero, and a non-number when reading to an int), and automatically deals with the trailing garbage. You'll have to convert the read string manually to whatever it is you actually want, though.



                  In your case, you could change the loop condition trivially to something like this:



                  string answer;
                  ...
                  getline(cin, answer);
                  } while (answer == "y" || answer == "Y");


                  If you need a number, you can use e.g. int num = std::stoi(str).




                  (In C, the same happens if using scanf() for user input, and similarly, it's better to use fgets() and then parse the string with sscanf(), which gives the same options but deals with line-buffering. I'm not too familiar with C++, so I can't tell how to have the exact equivalent of cin >> somevar with a full line read by getline().)






                  share|improve this answer






















                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote









                    I'm going to suggest something entirely the opposite of the other answers. Instead of using cin.ignore to skip any extra characters after the one you read, I think it's better to do all your reading with getline() and forget about cin >> somevar completely.



                    There are two reasons:



                    1. The formatted input you get with cin >> somevar ignores leading whitespace, including newlines. If the user hits Enter on an empty line the program doesn't do anything, but still expects further input. This is not what the user of a CLI program expects! The usual expectation is that Enter completes the input, and an empty input should either cause the program to use a default value, or to complain about invalid input. With cin >> somevar, you can't do either.



                    2. Formatted input leaves any unmatched input in the buffer. In your example, reading a single character leaves at least the following newline, but the same happens with other kinds of input. Reading a number (with int i; cin >> i;) leaves anything after the number waiting for the next input operation, so entering 123 abc will return 123, and the abc will appear on the next input operation.



                      The underlying cause of this is that by default, a command-line terminal is in a line-based mode. The program or the library functions don't see any input from the operating system until a complete line is entered. (cin.ignore() can of course help you deal with this, but not with the first point.)



                    Using getline() matches the underlying mechanic exactly, lets you deal with empty inputs (as well as telling the difference between a zero, and a non-number when reading to an int), and automatically deals with the trailing garbage. You'll have to convert the read string manually to whatever it is you actually want, though.



                    In your case, you could change the loop condition trivially to something like this:



                    string answer;
                    ...
                    getline(cin, answer);
                    } while (answer == "y" || answer == "Y");


                    If you need a number, you can use e.g. int num = std::stoi(str).




                    (In C, the same happens if using scanf() for user input, and similarly, it's better to use fgets() and then parse the string with sscanf(), which gives the same options but deals with line-buffering. I'm not too familiar with C++, so I can't tell how to have the exact equivalent of cin >> somevar with a full line read by getline().)






                    share|improve this answer












                    I'm going to suggest something entirely the opposite of the other answers. Instead of using cin.ignore to skip any extra characters after the one you read, I think it's better to do all your reading with getline() and forget about cin >> somevar completely.



                    There are two reasons:



                    1. The formatted input you get with cin >> somevar ignores leading whitespace, including newlines. If the user hits Enter on an empty line the program doesn't do anything, but still expects further input. This is not what the user of a CLI program expects! The usual expectation is that Enter completes the input, and an empty input should either cause the program to use a default value, or to complain about invalid input. With cin >> somevar, you can't do either.



                    2. Formatted input leaves any unmatched input in the buffer. In your example, reading a single character leaves at least the following newline, but the same happens with other kinds of input. Reading a number (with int i; cin >> i;) leaves anything after the number waiting for the next input operation, so entering 123 abc will return 123, and the abc will appear on the next input operation.



                      The underlying cause of this is that by default, a command-line terminal is in a line-based mode. The program or the library functions don't see any input from the operating system until a complete line is entered. (cin.ignore() can of course help you deal with this, but not with the first point.)



                    Using getline() matches the underlying mechanic exactly, lets you deal with empty inputs (as well as telling the difference between a zero, and a non-number when reading to an int), and automatically deals with the trailing garbage. You'll have to convert the read string manually to whatever it is you actually want, though.



                    In your case, you could change the loop condition trivially to something like this:



                    string answer;
                    ...
                    getline(cin, answer);
                    } while (answer == "y" || answer == "Y");


                    If you need a number, you can use e.g. int num = std::stoi(str).




                    (In C, the same happens if using scanf() for user input, and similarly, it's better to use fgets() and then parse the string with sscanf(), which gives the same options but deals with line-buffering. I'm not too familiar with C++, so I can't tell how to have the exact equivalent of cin >> somevar with a full line read by getline().)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 4 hours ago









                    ilkkachu

                    3,302317




                    3,302317




















                        up vote
                        0
                        down vote













                        Since you are taking input from the user of type char but every Enter key hit, it assigns the newline (n) to the variable answer.



                        You can ignore this by adding a line just after the input line



                        cin.ignore();


                        You may read this for more details.






                        share|improve this answer
























                          up vote
                          0
                          down vote













                          Since you are taking input from the user of type char but every Enter key hit, it assigns the newline (n) to the variable answer.



                          You can ignore this by adding a line just after the input line



                          cin.ignore();


                          You may read this for more details.






                          share|improve this answer






















                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Since you are taking input from the user of type char but every Enter key hit, it assigns the newline (n) to the variable answer.



                            You can ignore this by adding a line just after the input line



                            cin.ignore();


                            You may read this for more details.






                            share|improve this answer












                            Since you are taking input from the user of type char but every Enter key hit, it assigns the newline (n) to the variable answer.



                            You can ignore this by adding a line just after the input line



                            cin.ignore();


                            You may read this for more details.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 7 hours ago









                            Shravan40

                            4,06221531




                            4,06221531




















                                JKisa is a new contributor. Be nice, and check out our Code of Conduct.









                                 

                                draft saved


                                draft discarded


















                                JKisa is a new contributor. Be nice, and check out our Code of Conduct.












                                JKisa is a new contributor. Be nice, and check out our Code of Conduct.











                                JKisa is a new contributor. Be nice, and check out our Code of Conduct.













                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52717083%2fif-statements-in-a-do-while-loop-with-a-yes-or-no-ending%23new-answer', 'question_page');

                                );

                                Post as a guest













































































                                Comments

                                Popular posts from this blog

                                Long meetings (6-7 hours a day): Being “babysat” by supervisor

                                Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

                                Confectionery