Do I need to change stdin if I initial use 'filename' as stdin and then I need to go back to traditional consol stdin?

StackOverflow https://stackoverflow.com/questions/22159134

  •  19-10-2022
  •  | 
  •  

Question

./dataset < filename

// I Read the data into a file and store it into arrays...

...

// Here I need to ask the user for a number, however, the program always skip the user input and continues...

char answer; answer = getchar(); // Always skip the getchar()

No correct solution

OTHER TIPS

No, that's not the way to do it. No idea if it would work, but wouldn't it be a lot easier to just open the file, read it and reserve stdin for your interaction with the user?

FILE *yourinputfile;

yourinputfile=fopen("whatevernamethefilehas","r");
// read with the appropriate routines, eg fscanf

fclose (yourinputfile);

char answer; answer = getchar(); // won't skip now

You'll notice that all input routines in C have a "shorthand" variety that reads stdin, and a variety that starts with f that will read a file

  • scanf and fscanf
  • gets and fgets
  • etc

The man pages are your friend :)

If you're allowed to use concurrency, you could fork() a new process and dup2() stdin to a new file descriptor in your child process. You want to make sure not to dup2() your stdin on your main process or else you'll lose the ability to read from stdin.

Happy to go into more detail if this seems like the right detail of direction

Edit: Can you share how you've "stopped" reading in from traditional stdin? I'm confused because normally reading from a file should not stop you from being able to read from stdin.

Edit2 - I think fvu is right, if you look at the page you linked to you, theres an answer that talks about using dup2() to copy the stdin file descriptor to a temp file descriptor, replace the file descriptor for stdin with something else, and then replace it again with its temp copy. That sounds like what you're looking for

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top