echoing of getchar and '\\n' char from std

2019-08-14 04:03发布

问题:

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