echoing of getchar and '\n' char from stdin

纵饮孤独 提交于 2019-12-11 05:09:29

问题


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;
}

Thanks Lachlan


回答1:


For a start try with the following :

1) the condition should be if (c != '\n' && c != '\r')

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);
    }


来源:https://stackoverflow.com/questions/10185507/echoing-of-getchar-and-n-char-from-stdin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!