我最近购买了C编程语言,并尝试了Ex1-8,这里是代码
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/*
*
*/
int main() {
int nl,nt,nb;
int c;
printf("\nHello and Welcome :D\nThis is the 'answer' to Ex 1-8 in TCPG\nRemember,to end input,type in %d\n[Press <ENTER> to continue]\n",EOF);
getch();
for(nl = 0,nb = 0,nt = 0;(c = getchar()) != EOF; ) // When getchar is replaced by getche() it goes into the loop but doesnt exit the loop
{
putchar(c);
if(c == '\n')
{
nl++;
}
else if(c == '\t')
{
nt++;
}
else if(c == ' ')
{
nb++;
}
}
printf("\nYou typed in %d blanks, %d tabs and wrote %d lines\n[Press <ENTER> to exit]",nb,nt,nl);
getch();
return (EXIT_SUCCESS);
}
它就是不会进入循环!当getchar()被替换为getche()时,它会进入循环,但不会退出:(如果你没有猜到,putchar(c);只是为了确认它已经进入了循环这一事实我尝试了Ctrl +D和Ctrl +Z我正在使用Windows 8感谢各位:)
编辑:我最初使用的是开关盒结构,但我想我应该按照书上说的去做,我只是在输入一点后看到书上写着运行失败(退出值-1,总时间: 5s)……有什么想法吗?谢谢大家:) (再说一遍:D )
发布于 2013-08-31 13:03:31
首先,您不应该使用或getch/ getche,这些不是标准C。当您在循环中使用getche时,问题是MS Windows上的此函数不处理文件结束控制。
一般来说,第一个getchar()调用直到您为第一行按enter键之后才会返回,所以如果您期望它立即“进入循环”,那么您就错了。只需继续键入并按enter即可。
https://stackoverflow.com/questions/18544252
复制相似问题