Specification: Display a menu
Find Errors in this program

#include "stdafx.h"
#include <iostream> //change io to iostream
#include <string>
using namespace std; // added

I get the Error 1 error C2065: 'choice' : undeclared identifier line 17 which is 'choice'

What am i missing?

int main ()// added int
{ //reversed this symbol


cout << "Choose From Martha's Menu:\n"; //reversed <<
cout << "1 - Dinner"; // added ;
cout << endl << " 2 - Lunch"; //correct endl and added ;
cout << endl << "3 - Breakfast"; //corrected endl and added ;
cout << "Enter a number:";
std::cin >> choice;
int choice = 0;
cout << "You Choose " << choice;


;return 0;
}

Dani AI

Generated

The MSVC error C2065 "'choice' : undeclared identifier" means the compiler never saw a declaration for that name at the point it was used. As pointed out, the input operation in the original snippet occurs before the variable is declared — the compiler processes code top-to-bottom and must know a symbol's declaration before any use. The immediate fix is to declare (and preferably initialize) the variable before reading into it; additionally, validate input to avoid runtime surprises.

#include <iostream>

int main() {
    int choice = 0;                  // declare before using
    std::cout << "Enter a number: ";
    if (!(std::cin >> choice)) {
        std::cerr << "Invalid input\n";
        return 1;
    }
    std::cout << "You chose " << choice << '\n';
    return 0;
}

Quick checklist for C2065 and similar "undeclared identifier" errors:

  • Declaration order: move the declaration above the first use.
  • Typos and case sensitivity: C++ identifiers are case-sensitive.
  • Scope: ensure the declaration is visible (not inside a different pair of braces).
  • Missing header or qualification: e.g., std::cin/std::cout require <iostream> or std:: prefix.
  • Precompiled headers (MSVC): if a project uses stdafx.h, include it first.
  • Earlier syntax errors: a missing semicolon or brace on a previous line can produce misleading undeclared-name errors.

A few practical habits: initialize variables at declaration, check stream extraction results, enable compiler warnings, and use the IDE’s error navigator to jump to the exact problem line. These reduce the chance of simple ordering/scope mistakes like the one in ’s snippet.

Recommended Answers

All 2 Replies

Next time please use the code tags

[code]

code goes here

[/code]

Why do you declare choice after you try to write to it? You need to move int choice = 0; before std::cin >>choice;

Thank you so much! I cant believe it was right in front my my face.

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.