简体   繁体   English

C while循环 - 代码不起作用

[英]C while loop - code won't work

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, which will make it exit. 程序应逐个输入字符作为输入,直到输入%,这将使其退出。 It checks if input chars are vowels, and prints the result. 它检查输入字符是否为元音,并打印结果。 Also it reports an error if input is not a letter. 如果输入不是字母,它也会报告错误。 The problem is, it breaks out of the loop on the second step. 问题是,它在第​​二步中突破了循环。 Thank you for help, in advance. 提前谢谢你的帮助。 PS Sorry, didn't write that there's no error message, it just breaks out of the loop. PS抱歉,没有写出没有错误消息,它只是突破了循环。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
  char processed='q';
  while(processed != '%')
  {
    printf("Enter letter to check if it's a vowel, %% to quit.\n");
    char input = getchar();
    processed = tolower(input);
    printf("%c\n", processed);
    if (processed == '%')
      break;
    if (processed < 'a' || processed > 'z')
    {
      fprintf(stderr, "Input should be a letter\n");
      exit(1);  
    }
    switch(processed)
    {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
      case 'y':
        printf ("Vowel\n");
        break;
      default:
        printf ("Non-vowel\n");
    }
  }
  exit(0);
}

Presumably you're entering a character and then hitting [ENTER]. 想必你正在输入一个角色,然后点击[ENTER]。 So, in actuality you are entering two characters -- the letter you typed and a line feed ( \\n ). 因此,实际上您输入了两个字符 - 您输入的字母和换行符( \\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;
}

Someone else mentioned that you're hitting enter after each letter of input, and thus sending a newline ('\\n') into your program. 有人提到你在每个输入字母后输入,然后在你的程序中发送换行符('\\ n')。 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. 您可以添加代码来处理换行符,但使用scanf会更容易。 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. scanf()将处理换行符并返回您感兴趣的字母。

And you should check scanf()'s return value for errors, of course. 当然,你应该检查scanf()的错误返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM