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
答案 0 :(得分:0)