C while loop - code won't work

后端 未结 2 998
轻奢々
轻奢々 2021-01-22 08:48

I\'ve been writing a simple program to check if input letter is a vowel, and my code doesn\'t work. The program should take characters as input one by one until % is entered, wh

相关标签:
2条回答
  • Presumably you're entering a character and then hitting [ENTER]. So, in actuality you are entering two characters -- the letter you typed and a line feed (\n). The second time through the loop you get the line feed and find that it's not a letter, so you hit the error case. Perhaps you want to add something like:

    if (processed == '\n') {
        continue;
    }
    
    0 讨论(0)
  • 2021-01-22 09:53

    Someone else mentioned that you're hitting enter after each letter of input, and thus sending a newline ('\n') into your program. Since your program doesn't have a case to handle that, it isn't working right.

    You could add code to handle the newline, but using scanf would be easier. Specifically, if you replaced

    char indent = getchar();
    

    with

    char indent;
    scanf("%c\n", &indent);
    

    scanf() would handle the newline and just return back the letters you're interested in.

    And you should check scanf()'s return value for errors, of course.

    0 讨论(0)
提交回复
热议问题