Reading input from console while input redirection

Hello.
I'm working on a project that uses input redirection to read text from a file. Everything worked fine until I needed to search for a word that user inputs in a console...

So, something like this>
 
  >program.exe < input.txt

and after this line my program asks the user 'Please input the word you want to search for in a document'. Now, when I try to scanf that word, program crashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
  char word[20], line[20];
  char c;

  printf("What word to search for?\n");  //it prints out this line and crashes
  scanf("%[^\n]", word);
  scanf("%s", word);
  printf("Word we are searching for is: %s\n", word);

  do {
    c = fscanf(stdin,"%s",line);  //i know this do-while works
  //some other code
  } while (c != EOF);

  return 0;
}


Does anybody know whats the problem?
Last edited on
simply don't redirect the input, use the arguments to main to open a file.
1
2
3
4
//$ program input.txt
int main(int argc, char **argv){
   if(argc not_eq 2) return 1;
   FILE *input = fopen(argv[1], "r");
Yes, I have thought of that. And, even then you can redirect input:

1
2
3
4
5
6
7
 >program.exe word < input.txt

int main(int argc, char *argv[])
{
  char word[20];
  //somehow copy argv[1] to word
}


I know its possible to do it this way, however I need to use scanf() to aquire word and that is what is bugging me.
then use stdin to read from standar input and a FILE* to read from the file.
c = fscanf(input,"%s",line); //line 12
Topic archived. No new replies allowed.