echoing of getchar and '\n' char from stdi

2019-08-14 04:12发布

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条回答
倾城 Initia
2楼-- · 2019-08-14 04:39

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);
    }
查看更多
登录 后发表回答