Trouble with User Input & Error Checks

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Error Input
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
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.