Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c - Change input stream mid-program

I have the following program which prints text from a file:

#include<stdio.h>
int main(void) {
    int ch;

    while ((ch=getchar()) != EOF) {
        putchar(ch);
    }

    printf("Enter a character now...
");
    // possible to prompt input now from a user?
    ch = getchar();
    printf("The character you entered was: %c
", (char) ch);

}

And running it:

$ ./io2 < file.txt
This is a text file
Do you like it?
Enter a character now...
The character you entered was: ?

After this, how would I get a user to enter in a character. For example, if I were to do getchar() (when not redirecting the file to stdin)?

Now it seems it just will keep printing the EOF character if I keep doing getchar() at the end.

question from:https://stackoverflow.com/questions/65910836/change-input-stream-mid-program

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My previous suggestion won't work because the cat command will just join both the file and stdin as one and supply that to your program and you will eventually reach the same conclusion.

If your program needs the file, it should just read from it directly, then get the rest of its input from standard input...

#include<stdio.h>
#include<stdlib.h>
int main(void) {
    int ch;
    FILE* file = fopen("file.txt", "r");
    if (file == NULL) {
        perror("fopen");
        return EXIT_FAILURE;
    }

    while ((ch=fgetc(file)) != EOF) {
        putchar(ch);
    }

    fclose(file);
    ... // now just read from stdin

    return EXIT_SUCCESS;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...