首页 > C 语言为什么这个 while 循环中判定式值为假值了也不会结束?

C 语言为什么这个 while 循环中判定式值为假值了也不会结束?

rt,我是C语言初学者,今天做习题的时候遇到这个问题
代码:

#include <stdio.h>
#include<stdlib.h>

int main(void)
{
char first, last, ch;

printf("Enter a first and last name: ");
first = getchar();
while ((ch = getchar()) != ' ')
{
    ch = getchar();
    if (ch == '\n' || ch == ' ')
        break;
}

while ((last = getchar()) != ' ' )
    printf("%c", last);

printf(",%c.", first);
system("pause");
}

最后一个while循环输出完 需要的东西之后并不结束,但是表达式的值已经为假值了,因为getchar提取到缓冲区的最后一个字符是'\n'。但是循环并不结束,只有人为在循环中加入:

if ((last = getchar()) != '\n')
{
    break;
}

循环才会在getchar遇到\n才会结束

这是为什么?
谢谢!


海量技术文章:http://tieba.yunxunmi.com/


你敲一下空格+回车试试?


虽然不是非常清楚你程序的运行目的,但是如果剩余的字符串中没有空格,while ((last = getchar()) != ' ')printf("%c", last);一句不显然是死循环么,因为当字符串被读完后,getchar()会返回EOF,也就是-1,使得表达式恒为真啊


getchar必须在有换行的时候才会读入字符,因为终端里stdin有个行Buffer,必须在换行时才会对把数据送入程序里。

所以你得 空格 + 回车 才奏效

【热门文章】
【热门文章】