从标准输入中回显getchar和'\n'char [英] echoing of getchar and '\n' char from stdin

查看:154
本文介绍了从标准输入中回显getchar和'\n'char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过了这个类似问题,但是我仍然想知道是否还有另一种方法可以停止1)终端以可移植性呼应,因为这是一项任务,我已经有一个Java程序崩溃并在教师计算机上刻录了2)在我的程序中,我搜索'\n' char,如果不是第一个字符,则使用 getchar ,然后使用 putchar 直到下一个'\n'字符,当使用重定向的 stdin 时可以正常工作,但是当我尝试使用程序而不进行重定向,回车键始终被回显,这与终端回显有关还是我需要检查除'\n'?我也尝试过包含'/ r'并进行了大量的谷歌搜索,但似乎回声的答案无法通过可移植性来完成?

I have already looked at this similar question but i am still wondering if there is another way to stop 1) the terminal echoing with portabilty as this is an assignment and I have already had one java program crash and burn on my teachers computer 2) in my program i search for a '\n' char then if it isn't the first char use getchar then putchar till the next '\n' char which works fine when using redirected stdin but when I try using the program without redirection the enter key is always echoed, is this to do with the terminal echoing or do i need to check for a diffrent char apart from '\n'? I have also tried including '/r' and done lots of googling but it seems the answer to the echo is can't be done with portabilty?

#include <stdio.h>
#include <string.h>

int first_line(char);
int main(){
    
char c;

while((c = getchar())!=EOF){
    first_line(c);
}   

return 0;
}

int first_line(char c){
if (c != '\n'||c != '\r'){
    putchar(c);

    do{
        c = getchar();
        putchar(c);}
    while( c !='\n');
}

return 0;
}

感谢Lachlan

推荐答案

首先尝试以下操作:

1)条件应为 if(c!='\ n'&& c!='\r')

2)和while循环,如果终端是行缓冲后,最好使用ncurses库中的 getch ,该库包对于大多数平台都应该存在。

2) and the while loop ,in case if terminal is line buffered then you are better of using getchfrom ncurses library the library packages should be there for most platforms.

    while((c =getchar())!='\n') {
       putchar(c);
    }

这篇关于从标准输入中回显getchar和'\n'char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆