0

So I am currently writing a program in C that using a switch statement can allow a string to be entered then depending on the value you choose from the menu determine what to do with it.

Here is my code,

#include <stdio.h>


int main()
{
    int menu, end, i;
    char string[100];
    end = 0;

    do
    {
        printf("Welcome to the string operations program.\n\n");

        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        scanf("%d", &menu);

        switch (menu)
        {
            case 1:
                printf("String: ");
                scanf("%s", string);
                break;

            case 2:
                printf("This is a message: Hello %s\n", string);
                break;

            case 3:
                printf("There are %d characters in %s\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (i = strlen(string) - 1; i >= 0; i--)
                    printf("%c", string[i]);
                printf("\n");
                break;

            case 5:
                printf("Exit");
                return 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;


        }
    }while (end != 1);
    return 0;
}

It seems to work for everything when I run it through 1,2,3,4,5 as that is the requirement for the question. However when i enter a letter for example 't' it goes to the default section as expected. When it enters this it goes into an infinite loop.

Can anyone help me and show me how to not make this an infinite loop but just have it return to the start as the user input was not allowed?

Liam
  • 139
  • 3
  • 11
  • 2
    You're reading a number with `scanf("%d", ...);`, but since you put something else in there (i.e., 't'), and **never remove it**, it loops. You would have to flush the input stream of all values before asking the user to once again enter a value. Check here: https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c – AntonH Nov 16 '17 at 22:20
  • HAve you debugged and checked the value of `end`? – t0mm13b Nov 16 '17 at 22:20
  • Ah I understand! thank you for the help! @AntonH – Liam Nov 16 '17 at 22:47
  • And @user3121023 – Liam Nov 16 '17 at 22:47
  • the posted code does not cleanly compile. it is missing `#include ` for the `strlen()` function, Note: `strlen()` returns type `size_t`, not `int`, so in the call to `printf()` the format specifier should be '%lu' rather than '%d'. in the `for (i = strlen(string) - 1; i >= 0; i--)` statement the variable 'i' is declared as 'int' but is being compared to a 'size_t' Suggest declaring 'i' via `size_t i;` – user3629249 Nov 17 '17 at 17:21
  • when calling any of the `scanf()` family of functions, 1) always check the returned value (not the parameter values) to assure the operation was successful. 2) when using the '%s' input format specifier, always include a MAX CHARACTERS modifier that is one less than the length of the input buffer because '%s' always appends a NUL byte to the input. – user3629249 Nov 17 '17 at 17:24
  • regarding case 5. it should contain: `printf( "Exit"); end = 1; break;` Note: otherwise, 'end' will NEVER be set to 1. And returning `1` from main() is indicating to the system that the program failed. – user3629249 Nov 17 '17 at 17:28
  • the posted code has a logic error. What happens when the user selects some other menu item before entering a string? – user3629249 Nov 17 '17 at 17:38

2 Answers2

1

there are several problems with the posted code:

  1. does not handle the scenario when the use has not entered a string
  2. displays the welcome message more than once
  3. does not properly handle menu selection 5
  4. does not 'compare apples to apples'
  5. does not empty stdin before trying input a string
  6. does not allow any white space in the input string
  7. ....

The following proposed code:

  1. corrects all the above listed problems
  2. cleanly compiles
  3. properly checks for and reports errors
  4. contains a default string so the program does not have undefined behavior
  5. includes the needed header files and documents why each header file is being included

And now the proposed code:

#include <stdio.h>   // printf(), scanf(), fprintf()
#include <stdlib.h>  // exit(), EXIT_FAILURE
#include <string.h>  // strlen()


int main()
{
    int menu;
    int end;
   //int i;
    char string[100] = "no string entered";
    end = 0;

    printf("Welcome to the string operations program.\n\n");

    do
    {
        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        if( 1 != scanf("%d", &menu) )
        {
            fprintf( stderr, "scanf for menu selection failed\n" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful

        switch (menu)
        {
            case 1:
                // note leading space in format string to consume leftover newline in 'stdin'
                printf("String: ");
                if( 1 != scanf(" %99[^\n]", string) )
                {
                    fprintf( stderr, "scanf for input string failed\n" );
                    exit( EXIT_FAILURE );
                }

                // implied else, scanf successful
                break;

            case 2:
                printf("This is the string entered: <%s>\n", string);
                break;

            case 3:
                // note appropriate format specifier for `size_t` from `strlen()`
                printf("There are %lu characters in <%s>\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (size_t i = strlen(string); i; i--)
                    printf("%c", string[i-1]);

                printf("\n");
                break;

            case 5:
                printf("Exit");
                end = 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;
        }
    } while (end != 1);
    return 0;
}

A run of the program results in the following output:

Welcome to the string operations program.

1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 2
This is the string entered: <no string entered>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 1
String: this is a string with spaces
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 2
This is the string entered: <this is a string with spaces>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 3
There are 28 characters in <this is a string with spaces>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 4
string reversed gives: secaps htiw gnirts a si siht
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 6
Invalid input, try again.
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 5
Exit
user3629249
  • 16,402
  • 1
  • 16
  • 17
  • Thank you for giving this in depth answer! I am aware of the problems which you have posted however I have made it this way as that is exactly how it is described to me in the brief, that is because it is simply a small exercise during a Lab to make use create a small switch statement. I was never designed to be useful etc. But still thank you very much for you input it was interesting none the less! – Liam Nov 19 '17 at 18:54
0

Like Anton mentioned the problem is because of the scanf statement. You can add a getchar(); before break; in default: to solve this problem. Two more suggestions: * You can remove the do-while loop here as it serves no special purpose and it's better to use while(1) loop. * Also the break; statement in case 5 is not needed.