Trouble with User Input & Error Checks

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Error Input
AI Thread Summary
The discussion highlights issues with user input and error checks in a program's loop. After an initial error, subsequent iterations incorrectly display multiple error messages, including those for file openings that should not appear. The code structure requires users to input four separate values regardless of previous errors, leading to confusion. Additionally, the lack of prompts for user guidance exacerbates the problem. Improving the error handling and providing clear prompts would enhance user experience significantly.
magnifik
Messages
350
Reaction score
0
i'm having trouble with user input & error checks. after the first iteration, if there is an error, the correct error message shows up. but for the next iterations, the error messages for the opening of the input and output files show along with the correct one. idk if that made any sense...

screen should look like:
e power input.txt output.txt

with an error it looks like:
a power input.txt output.txt
Command not allowed. Try again.

e p0wer input.txt output.txt
Key invalid. Try again.
Can't open file input.txt. Try again. // this should not show
Can't open file output.txt. Try again. // this should not show

Code:
int main(){
	char choice;
	string key;
	char inputFile[500];
	char outputFile[500];
	for(;;){
		cin >> choice;
		if (choice != 'e' && choice != 'd')
			cout << "Command not allowed. Try again." << endl;
		cin >> key;
		for (int i = 0; i < key.length(); i++){
			if(!isalpha(key[i]))
				cout << "Key invalid. Try again." << endl;
		}
		cin >> inputFile;
		inFile.open(inputFile);
		if (!inFile)
			cout << "Can't open file " << inputFile << ". Try again." << endl;
		cin >> outputFile;
		outFile.open(outputFile);
		if (!outFile)
			cout << "Can't open file " << outputFile << ". Try again." << endl;
	}
}
 
Physics news on Phys.org
Think about what happens during each iteration of your for loop. You are asking for four different inputs regardless of whether the user typed a wrong command or invalid file name or whatever. For this reason, the "Try again." requests when the user enters erroneous input are very misleading, because the user doesn't get a chance to re-enter the bad input in that iteration of the for loop.

Besides this, there are no prompts to guide the poor user to what he should be entering.
 

Similar threads

Replies
6
Views
3K
Replies
23
Views
3K
Replies
3
Views
2K
Replies
3
Views
1K
Replies
14
Views
3K
Replies
2
Views
10K
Back
Top