0

./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()

2 Answers2

0

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 :)

fvu
  • 32,488
  • 6
  • 61
  • 79
  • Yeah this would be easier, but teachers like to make it complicated... I get what you have suggested, I just can't do it like this... I need to redirect the file like this ./dataset < filename and then get user input... – user3366297 Mar 03 '14 at 23:00
  • There's a couple of related questions here on SO, like http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c maybe that will help? Still don't think it's a good idea though, but if that what's prof wants, well you don't have much choice... – fvu Mar 03 '14 at 23:13
0

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

MoMo
  • 499
  • 3
  • 12
  • I am not sure if fork() will do... I am not trying to duplicate the process, just to stop reading from 'filename' and start reading again from the 'traditional' stdin – user3366297 Mar 03 '14 at 23:20