-1

At Uni we have to programm LIFE and have to make therefore a menu. To read the user's input of the menu we should write a reading function which processes/removes the newlines/enter. We wrote following:

char reading ( ) {
    char input ;
    while (input != '/n') {
        cin.get (input) ;
        return input;
    } 
} 

If we replace now cin with this function it prints our menu twice after we enterd the first menu option. If we enter something like kkk which is no option of the menu, it prints the menu 4 times. I asked one of the helping assistants and he didn't know and found that the function seems correct and that it is probably something very obvious what he doesn't know right now. It's also said to be nothing wrong with our menu-code. Do you have an idea what maybe went wrong and can explain it to me? Thanks a lot!

Positron
  • 1
  • 2
  • 6
    Even if he did initialse it, the code is almost completely wrong, and seems to have been written at random. To the OP: " I asked one of the helping assistants and he didn't know and found that the function seems correct" - go to another seat of learning. –  Nov 09 '17 at 21:06
  • Yes I meant that, thanks for letting know! – Positron Nov 09 '17 at 21:15
  • 3
    None of the code makes sense. You test the input *before* you even acquire the input. You exit the function immediately after getting the input without even testing it. You should understand what **every** statement in the function does. If you don't, [go to a book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and ***look it up***. – Galik Nov 09 '17 at 21:15

1 Answers1

1

You never initialize input, so when reading it the first time in your loop you have Undefined Behaviour and your program in its entirety is thus meaningless. Reading uninitialized variables is UB, plain and simple.

There are other problems with your code as well (like not always returning a value from your function that's declared to return char), but UB beats all - as long as the code has UB, nothing else really matters.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70