Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
El menú se imprime dos veces y el valor predeterminado se ejecuta incluso cuando las mayúsculas y minúsculas no coinciden

Estoy tratando de mostrarle al usuario un menú y permitirle elegir entre las opciones. Está en un ciclo while porque tiene que iterar hasta que se elija la opción "e" para salir del programa. Incluí la opción "predeterminada" como una prueba de fallas si el usuario ingresa un valor que no se acepta. El caso predeterminado siempre se ejecuta sin importar lo que haga y el menú siempre aparece dos veces después de la ejecución inicial del código. Intenté cambiar "getchar ()" a scanf y todavía produce el mismo resultado duplicado. También he intentado eliminar el cambio por completo, pero obtengo el mismo resultado usando declaraciones si/entonces. ¡He adjuntado mi código completo y cualquier ayuda es apreciada, gracias!

 #include <stdio.h> #include <stdlib.h> // function for the menu char menu() { printf("Please select from the following menu: \n"); // setting up the menu from here printf("a. input the data files location \n"); printf("b. enter the time interval \n"); printf("c. process and display the US Life Expectancy Data \n"); printf("d. process and display the Statistics of All Data \n"); printf("e. exit the program \n"); } char options(char choice) { switch (choice) { case 'a': printf("choice a\n"); break; case 'b': printf("choice b\n"); break; case 'c': printf("choice c\n"); break; case 'd': printf("choice d\n"); break; case 'e': break; default: // default when none of the cases are matched printf("Invalid input\n"); break; } } // main function int main(void) { char choice; do { menu(); while ((choice = getchar()) == "\n") {}; if (choice == EOF) { exit(1); } options(choice); } while (choice != 'e'); }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

El problema es que su código no maneja nuevas líneas. En otras palabras, cuando escribe a seguido de ENTER, su código en realidad recibe dos caracteres. La 'a' y la '\n' . Por lo tanto, el menú se imprimirá dos veces y obtendrá una "entrada no válida".

Una solución rápida podría ser:

 choice = getchar(); --> while ((choice = getchar()) == '\n') {};

Dicho esto, deberías cambiar la choice para que sea un int y también hacer:

 int choice; .... .... while ((choice = getchar()) == '\n') {}; if (choice == EOF) { // Fatal input error exit(1); }

Finalmente, es una mala idea tener choice como global. En su lugar, póngalo en main y páselo como argumento a las options de la función. Pero no lo pases al menu . Así que hazlo:

 char options() { --> char options(int choice) {

y

 int main(void) { int choice; do { menu(); while ((choice = getchar()) == '\n') {}; // ignore newlines if (choice == EOF) { // Fatal input error exit(1); } options(choice); } while (choice != 'e'); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!