【问题标题】:Trying to have error correction while prompting to run program again在提示再次运行程序时尝试进行错误更正
【发布时间】:2017-04-19 18:18:57
【问题描述】:

C++ 新手。我有一个正在编程的家庭作业程序。一切都差不多完成了,但是我们的老师希望我们在程序中添加错误捕获。

问题出现在要求用户再次运行的代码中。我使用 while 循环来监视变量,直到它发生变化。

这行得通:

#include <iostream>
using namespace std;

int main() {
    char runAgainYN;

    while ( toupper(runAgainYN != 'N' ) {
        // Do some stuff here!

        cout << "Would you like to run again?";
        cin >> runAgainYN;
    }

    return 0;
}

它一直循环程序直到 runAgain 等于 'N',然后停止。现在,我修改了程序,对再次运行程序的问题进行了一些纠错,以限制用户只能输入 Y 或 N。以下是更新的代码:

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

int main() {
    char runAgainYN;
    bool runAgain = true;

    while ( runAgain ) {

        // Do some stuff here!

        bool validResponse = false;
        while ( !validResponse ) {
            cout << "Would you like to run the program again (Y/N): ";
            cin >> runAgainYN;
            if ( toupper(runAgainYN) == 'Y' ) {
                validResponse = true;
                cin.ignore();
            }
            else if ( toupper(runAgainYN) == 'N' ) {
                runAgain = false;
                validResponse = true;
                cin.ignore();
            }
            else {
                cout << "INVALID RESPONSE" << endl;
            }
        }
    }

    return 0;
}

这就是问题出现的地方。如果用户输入“N”,则程序以代码 0 退出,如果用户输入除 Y 或 N 以外的任何内容,则会触发无效响应并再次要求输入。但是,如果用户输入 Y,程序将以代码 -1 退出。嗯?我尝试了不同的方法,结果相同:

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

int main() {
    char runAgainYN;

    do {
        // Do some stuff here!

        bool validResponse = false;
        while ( !validResponse ) {
            cout << "Would you like to run the program again (Y/N): ";
            cin >> runAgainYN;
            if ( toupper(runAgainYN) == 'Y' ) {
                validResponse = true;
                cin.ignore();
            }
            else if ( toupper(runAgainYN) == 'N' ) {
                runAgain = false;
                validResponse = true;
                cin.ignore();
            }
            else {
                cout << "INVALID RESPONSE" << endl;
            }
        }
    }

    while ( runAgain );

    return 0;
}

有帮助吗?谢谢!!!

好的,所以它似乎是实际程序中的某些东西导致它。这是源代码:

#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include <cctype>
#include <limits>
#include <algorithm>
#include <fstream>
using namespace std;

void cls();
void printLine( int length );
void showCurrency( double dv, int width = 14 );

int main() {

    string itemName[999][2];
    double itemPrice[999][3];
    double salesTotal = 0.0;
    double salesTax = 0.0;
    double totalTax = 0.0;
    double taxRate = 0.0;
    double grandTotal = 0.0;
    double test = 0.0;
    int numLines = 0;
    string readLine;
    string temp;
    ifstream fileIn;
    string menuHeader = "Sales Receipt from File";
    char runAgainYN;
    bool runAgain = true;

    do { // Loop until runAgain false

        // Open the file and count the number of lines, then close for next operation:
        fileIn.open("cost.txt");
        while (!fileIn.eof()) {
            fileIn >> temp;
            numLines++;
            temp = "";
        }
        fileIn.close();

        // Open the file and move the data into the arrays, then close:
        fileIn.open("cost.txt");
        for ( int i = 0; i < numLines; i++) {
            fileIn >> itemName[i][1] >> itemPrice[i][1];
        }
        fileIn.close();

        cls();

        numLines = numLines / 2;

        cout << "/";
        printLine(80);
        cout << "\\" << endl;
        cout << "|" << setw(81) << "|" << endl;
        cout << "|" << setw(41 + (menuHeader.length() / 2)) << menuHeader << setw(40 - (menuHeader.length() / 2)) << "|" << endl;
        cout << "|" << setw(81) << "|" << endl;
        cout << "\\";
        printLine(80);
        cout << "/" << endl << endl;

        cout << "Enter the sales tax percentage (ie for 6% enter 6): ";

        // Ask for taxRate and error check:
        while (!(cin >> taxRate)) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "INVALID RESPONSE" << endl << "Please enter a number: ";
        }
        cout << endl;

        salesTax = taxRate / 100; // Convert sales tax to percentage

        for (int i = 0; i < numLines; i++ ) { // Set the running tax amounts
            itemPrice[i][2] = itemPrice[i][1] * salesTax;
            salesTotal = salesTotal + itemPrice[i][1];
            totalTax = totalTax + itemPrice[i][2];
        }

        //totalTax = salesTotal * salesTax; // Calculate tax

        grandTotal = salesTotal + totalTax; // Calculate grand total

        // Output:
        cls();

        cout << "/" << setfill('-') << setw(63) << "-" << "\\" << setfill(' ') << endl;
        cout << "|                        SALES RECEIPT                          |" << endl;
        cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;
        cout << "| " << left << setw(32) << "Sales item" << setw(13) << right << "Price" << setw(18) << "Tax |" << endl;
        cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;

        for ( int i = 0; i <= numLines - 1; ++i ){
            cout << "| " << left << setw(32) << itemName[i][1] << "$" << setw(12) << setprecision(2) << fixed << right << itemPrice[i][1] << setw(5) << "$" << setw(11) << itemPrice[i][2] << " |" << endl;
        }

        cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;

        cout << "| Total Sales" << setw(36);
        showCurrency(salesTotal);
        cout << " |" << endl;

        cout << "| Sales Tax (" << setprecision(0) << fixed << taxRate << "%)" << setw(33);
        showCurrency(totalTax);
        cout << " |" << endl;

        cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;

        cout << "| Grand Total" << setw(36);
        showCurrency(grandTotal);
        cout << " |"  << endl;

        cout << "\\" << setfill('-') << setw(63) << "-" << "/" << setfill(' ') << endl;

        cout << endl;

        // Clear vars and array for next run:
        salesTax = 0.0;
        totalTax = 0.0;
        salesTotal = 0.0;
        grandTotal = 0.0;
        memset(itemPrice, 0, sizeof(itemPrice));
        memset(itemName, 0, sizeof(itemName));

        // Ask if program is to be run again:
        bool validResponse = false;
        while ( !validResponse ) {
            cout << "Would you like to enter a new tax rate (Y/N): ";
            cin >> runAgainYN;
            if ( toupper(runAgainYN) == 'Y' ) {
                validResponse = true;
                cin.ignore();
            }
            else if ( toupper(runAgainYN) == 'N' ) {
                runAgain = false;
                validResponse = true;
                cin.ignore();
            }
            else {
                cout << "INVALID RESPONSE" << endl;
            }
        }
    }

    while ( runAgain == true );

    return 0;

}

void printLine( int length ) {
    for ( int i = 0; i < length; i++ ) {
        cout << "=";
    }
}

void cls() {
        // check OS and run correct clear screen (I do some of my coding in Linux :)
    #if (defined (_WIN32) || defined (_WIN64))
        system("CLS");
    #elif (defined (LINUX) || defined (__linux__))
        system("clear");
    #endif
}

void showCurrency(double dv, int width){
    /* Credit where credit is due:
     * The following code snippet was found at https://arachnoid.com/cpptutor/student3.html
     * Copyright © 2000, P. Lutus. All rights reserved.
     */

    const string radix = ".";
    const string thousands = ",";
    const string unit = "$";
    unsigned long v = (unsigned long) ((dv * 100.0) + .5);
    string fmt,digit;
    int i = -2;
    do {
        if(i == 0) {
            fmt = radix + fmt;
        }
        if((i > 0) && (!(i % 3))) {
            fmt = thousands + fmt;
        }
        digit = (v % 10) + '0';
        fmt = digit + fmt;
        v /= 10;
        i++;
    }
    while((v) || (i < 1));
    cout << unit << setw(width) << fmt.c_str();
}

这里是'cost.txt'的内容:

Books 45.01
Pens 21.03
Pencils 10.90
Hats 50.00
Caps 800.00
Food 1.00

【问题讨论】:

  • 你试过用调试器一步步调试吗?你确定不是你的“在这里做一些事情”导致你的程序崩溃吗?
  • 我无法复制。您的代码(带有while ( runAgain ){...})工作正常。
  • 无法在我的桌面上重现。您的构建/运行环境是什么?
  • 在最后的代码引用中我找不到 runAgain 的定义。确定您按照引用编译了该代码?

标签: c++ loops error-handling


【解决方案1】:

好吧,看来我明白了。文件操作在 do 循环中。我将它们移到循环之外,一切正常。谢谢!

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2023-01-11
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多