简体   繁体   中英

How to get user input in do/while loop?

I tried to use the do / while loop I asked about and fixed in my one function in int main to allow the entire program to be rerun if the user wants to, but it is rerunning the program without waiting for user input.

int main()
{
    int spoolnumber = 0;     // Number of spools to be ordered
    float subtotalspool = 0; // Spool sub total
    float shippingcost = 0;  // Shipping cost
    float totalcost = 0;     // Total cost
    char type = 'n';

    do {
        instruct();                     // Print instructions to user
        spoolnumber = spoolnum();       // calculate and store number of spools

        subtotalspool = stotalspool(spoolnumber);       // Calculate subtotal
        shippingcost = shipcost(subtotalspool);         // Calculate subtotal
        totalcost = tcost(subtotalspool, shippingcost); // Calculate final total

        // Print final output
        results(spoolnumber, subtotalspool, shippingcost, totalcost);     
        cout << "\n" << " Would you like to run the program again? [y/n]"; 
    }
    while (type != 'y');

    return 0;
}

You haven't added any code to accept user input. At the bottom of your loop, trying reading a character from cin into type .

Also, you may need to flush the output of cout first, before accepting the user input from cin .

You haven't read any input from the user. You could simply do:

cin >> type;

But really you want to be checking that it is succeeding too, eg not eof or other errors otherwise it's still possible to loop forever if the user pressed Crtl - D for example.

Checking if it succeeds:

if (!(cin >> type)) {
   // Reading failed
   cerr << "Failed to read input" << endl;
   return -1;
}

Which you could actually make part of the loop condition:

while (cin >> type && type != 'y');

The advice from Xeo about calling cin.ignore() is important to since you will almost certainly end up with more than just one char worth of input.

Well, you never ask for input, do you? Add the following after the cout line:

cin >> type;
cin.ignore(); // remove trailing newline token from pressing [Enter]

Now, you'll still need the usual testing, if the input was valid at all etc, but this should get you going.

You need to include a cin in order to retrieve user's decision:

For example:

cout << "\n" << " Would you like to run the program again? [y/n]"; 
cin >> someVariable;

That's because you're not prompting the user for input.

You'll be more successful if you try something like:

cout << "\n" << " Would you like to run the program again? [y/n]"; 
cin >> type;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM