如何在do/while循环中获取用户输入?

Sam*_*nna 1 c++ user-input

我尝试使用我询问的do/while循环并在我的一个函数中修复,int main以允许整个程序在用户想要的情况下重新运行,但它重新运行程序而不等待用户输入.

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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 8

您尚未添加任何代码来接受用户输入.在你的循环的底部,试图读取字符cintype.

此外,cout在接受用户输入之前,您可能需要先刷新输出cin.


Fle*_*exo 8

您尚未阅读用户的任何输入.你可以这样做:

cin >> type;
Run Code Online (Sandbox Code Playgroud)

但实际上你想要检查它是否也成功,例如不是eof或其他错误,否则如果用户按下它仍然可以永远循环Crtl- D例如.

检查是否成功:

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

您实际上可以参与循环条件:

while (cin >> type && type != 'y');
Run Code Online (Sandbox Code Playgroud)

Xeo关于调用的建议cin.ignore()很重要,因为你几乎肯定会得到不仅仅是一个char输入值.


Xeo*_*Xeo 6

好吧,你从不要求输入,是吗?cout在行之后添加以下内容:

cin >> type;
cin.ignore(); // remove trailing newline token from pressing [Enter]
Run Code Online (Sandbox Code Playgroud)

现在,你仍然需要通常的测试,如果输入有效等,但这应该让你去.