Hello

I have a program that prints a menu & the user is prompted to input a choice(1,2 or 3) if they input anything else, the output should be "Invalid Choice".

My Problem
is that if a user inputs anything other than 1,2 or 3, then the program crashes, instead of doing what it should do "Invalid Choice".

What I am essentially trying to do is make the menu loop continuously unless option 3 is input (option 3 = quit).

Any advice would be really helpful. Such as should I uuse a whole new method of making the menu loop?

#include <cstdlib>
#include <iostream>

using namespace std;

// function prototypes
void printMenu();
void decision(int action);

int main()
{
	int option;

        // loop to display menu, get user choice and perform required action

	while(option != 3) {
		printMenu();
		cin >> option;    // if I type anything other than 1,2,3 the program crashes
		decision(option);
	}


	//system("pause");
	return 0;
}

void printMenu()
{

	cout << "\tCrossword Helper " << endl << endl;
	cout << " 1 : Check if word is in dictionary " << endl;
	cout << " 2 : Find words in dictionary which match pattern " << endl;
	cout << " 3 : Quit " << endl << flush;

}

void decision(int action) {     // Are these variable & function names acceptable?

	string word;

	switch (action) {
	case 1:
		cout << "\nEnter word: \n" << flush;
		cin >> word;
		to_lower(word);
		if (binarySearch(words,word,0,nWord)) {
			cout << word << " is in the dictionary\n";
		}
		else
			cout << word << " is NOT in the dictionary\n";
		break;
	case 2:
		cout << "\nEnter word pattern with ? for missing letters\n" << flush;
		cin >> word;
		to_lower(word);
		search(words,nWord,word);
		break;
	case 3:
		// I dont think I need to put anything here because break will stop the function then main will return 0
		//system("pause");
		//return 0;
		break;
	default:
		cout << "Invalid Choice";
		break;
	}
}

Dani AI

Generated

Two things are causing the crash in 's snippet: the loop tests option before it is initialized (undefined behavior), and using cin >> option leaves cin in a failed state when a non-numeric string is entered. Both points were hinted at by and ; fixing them eliminates the crash.

A robust pattern is: initialize the menu variable, read an entire input line with std::getline, and then parse/validate that line (for example with std::istringstream). That consumes any stray characters, detects malformed input, and keeps the input state clean. 's char approach is simple and fine for single-character menus, and 's suggestion to use stringstreams points in the same direction — the example below combines those ideas into a safe loop that only calls decision with a validated integer.

#include <iostream>
#include <sstream>
#include <string>

int main() {
    int option = 0;
    std::string line;
    while (true) {
        printMenu();
        if (!std::getline(std::cin, line)) break; // EOF or error
        std::istringstream iss(line);
        if (!(iss >> option)) {
            std::cout << "Invalid Choice\n";
            continue;
        }
        iss >> std::ws;
        if (!iss.eof()) {
            std::cout << "Invalid Choice\n";
            continue;
        }
        decision(option);
        if (option == 3) break;
    }
    return 0;
}

Quick troubleshooting notes: always initialize option (e.g. int option = 0;), validate input before calling decision, and if keeping cin >> style reads use if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } to recover. This prevents crashes and keeps the menu looping until the explicit quit option.

Recommended Answers

All 7 Replies

Well i compiled the program and it seems to work just fine.

Are you sure, that the program crashes if INput is >4?

The problem seems to be if I input strings or characters, it crashes

Try checking cin.fail(). If it is true, something went wrong with the input operation.

Good Luck!

i ll use an if code to determine the input is char or integer, i think the program crashes because option is integer

Try to use char variable of choice. Then your code will be like this

//declaration
void decision(char action);
//implementation
void decision(char action) {     // Are these variable & function names acceptable?
 
	string word;
 
	switch (action) {
	case '1':
		cout << "\nEnter word: \n" << flush;
		cin >> word;
		to_lower(word);
		if (binarySearch(words,word,0,nWord)) {
			cout << word << " is in the dictionary\n";
		}
		else
			cout << word << " is NOT in the dictionary\n";
		break;
	case '2':
		cout << "\nEnter word pattern with ? for missing letters\n" << flush;
		cin >> word;
		to_lower(word);
		search(words,nWord,word);
		break;
	case '3':
		// I dont think I need to put anything here because break will stop the function then main will return 0
		//system("pause");
		//return 0;
		break;
	default:
		cout << "Invalid Choice";
		break;
	}
}

And main

int main()
{
	char option;
 
        // loop to display menu, get user choice and perform required action
 
	while(option != '3') {
		printMenu();
		cin >> option;    // if I type anything other than 1,2,3 the program works correctly
		decision(option);
	}
 
 
	//system("pause");
	return 0;
}

P.S. Also you can use getchar() or cin.get(), or _getche() mothod to get the char choice.
I hope it will help you.

Hello

I have a program that prints a menu & the user is prompted to input a choice(1,2 or 3) if they input anything else, the output should be "Invalid Choice".

My Problem
is that if a user inputs anything other than 1,2 or 3, then the program crashes, instead of doing what it should do "Invalid Choice".

What I am essentially trying to do is make the menu loop continuously unless option 3 is input (option 3 = quit).

Any advice would be really helpful. Such as should I uuse a whole new method of making the menu loop?

Did you initialize option ? you seem to be commenting //system("pause"); .Are you really using a standard compiler?

>>The problem seems to be if I input strings or characters, it crashes

First get whatever input in a temporary string and then use strtol to get your option

int option = 0 ;
    string option_string;
       
	while(option != 3) {
		printMenu();
		char *end;
		getline(cin, option_string);    
		option = strtol(option_string.c_str(), &end, 10);
		cout << "You enterd option" << option;
		decision(option);
	}

use stringstream. Convert string to numerics. To avoid all the integer
hassle.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.