首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ex1-8 C编程语言

Ex1-8 C编程语言
EN

Stack Overflow用户
提问于 2013-08-31 11:40:05
回答 1查看 328关注 0票数 0

我最近购买了C编程语言,并尝试了Ex1-8,这里是代码

代码语言:javascript
运行
复制
#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 )

EN

回答 1

Stack Overflow用户

发布于 2013-08-31 13:03:31

首先,您不应该使用或getch/ getche,这些不是标准C。当您在循环中使用getche时,问题是MS Windows上的此函数不处理文件结束控制。

一般来说,第一个getchar()调用直到您为第一行按enter键之后才会返回,所以如果您期望它立即“进入循环”,那么您就错了。只需继续键入并按enter即可。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18544252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档