2014-04-20 158 views
3

我是C编程新手。我正在做一个练习,问题如下所示:使用?:运算符和for语句编写一个程序,用于保存用户输入的字符,直到字符q被计入。for循环在C中运行两次

这里是我写的程序:

#include <stdio.h> 

main() 
{ 
    int x, i=0; 
    for (x = 0; x == 'q'? 0 : 1; printf("Loop %d is finished\n",i)) 
    { 
     printf("Enter q to exit!!!\n"); 
     printf("Please enter a character:\n"); 
     x=getc(stdin); 
     putc(x,stdout); 
     ++i; 
    } 
    printf("\nThe for loop is ended. Bye!"); 

    return 0;  
} 

的问题是:每次我进入一个“非Q”字的时候,循环似乎运行两次。 我不知道我的程序有什么问题。 请帮忙!

+2

好像你需要清除输入缓冲区,因为你正在阅读换行符,我想。 – zeitue

回答

1

循环运行两次,因为当您输入非q字符时,实际上输入了两个字符 - 非q字符和换行'\n'字符。 x = getc(stdin);stdin流读取非q字符,但换行符仍位于stdin的缓冲区中,该缓冲区在接下来的getc调用中读取。

您应该使用fgets从其他人建议的流中读取一行,然后您可以处理该行。此外,您应指定main的返回类型为int。我建议以下变化 -

#include <stdio.h> 

int main(void) 
{ 
    int x, i = 0; 

    // array to store the input line 
    // assuming that the max length of 
    // the line is 10. +1 is for the 
    // terminating null added by fscanf to 
    // mark the end of the string 
    char line[10 + 1]; 

    for (x = 0; x == 'q'? 0 : 1; printf("Loop %d is finished\n", i)) 
    { 
     printf("Enter q to exit!!!\n"); 
     printf("Please enter a character:\n"); 

     // fgets reads an input line of at most 
     // one less than sizeof line, i.e., 
     // 10 characters from stdin and saves it 
     // in the array line and then adds a 
     // terminating null byte 
     fgets(line, sizeof line, stdin); 

     // assign the first character of line to x 
     x = line[0]; 
     putc(x, stdout); 
     ++i; 
    } 
    printf("\nThe for loop is ended. Bye!"); 

    return 0;  
} 
4

当您输入一个非q字母时,您还可以点击输入,这是在第二个循环中读取的。

要使循环仅对每个输入运行一次,请使用fgets()一次读取整行输入,并检查输入字符串是否符合您的期望。

+0

那你怎么能让它只运行一次? – MechAvia

+0

换句话说,'getc(stdin)'有两个字符可以读取,而且它是工作的! – ultifinitus

+0

使用'scanf'代替 –

3

当您键入a,然后按Enter时,换行符将成为stdin流的一部分。读取a后,下次执行x=getc(stdin)时,x的值设置为\n。这就是循环的两次迭代得到执行的原因。

1

当你输入一个字符,说“X”,然后按回车,你居然输入两个字符,这是“x”和“\ n”也被称为换行(当你回车)。 '\ n'成为输入流的一部分,循环也被执行。

另外,尝试输入“xyz”并回车,循环将执行4次。对于每个'x','y','z'和'\ n'。

如果您希望代码为每个输入工作一次,请使用函数gets。

#include <stdio.h> 

main() 
{ 
    int i=0; 
    char x[10]; 
    for (; x[0]!='q'; printf("Loop %d is finished\n",i)) 
    { 
     printf("Enter q to exit!!!\n"); 
     printf("Please enter a character:\n"); 
     gets(x); 
     i++; 
    } 
    printf("\nThe for loop is ended. Bye!"); 

    return 0; 
} 

在这段代码中我们声明x作为一个字符串,则得到()函数读取我们进入整条生产线,然后在for循环的条件部分,我们检查字符串的第一个字符是“ q'或不。