I have a binary search function that will search for a word in an array, but before I can search the array I need to know what word to search for. I have written the code to ask the user for input, but the program prints out the request for input but doesn’t accept anything from the user. I was thinking it was a buffer issue, as I have an initial scanf in the program that loads all the character strings from an external file and places them in an array. I have tried using fflush after my initial scanf, and I tried rewriting the second one with gets, as pointed out in previous threads. Perhaps I am not implementing it correctly. Here’s what I have so far, any tips as to why the second scanf isn’t working is appreciated.
#include "set.h"
#include "sortAndSearch.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char names[320][30];
char str[30];
int i, j;
char *key;
int numOfWords;
char userWord[30];
Set set1, set2, set3;
//scan each char string into array names
for(i=0; scanf("%s", str) != EOF; i++){
strcpy(names[i], str);
}
//set number of words in file
numOfWords = i;
//sort names array
//bubbleSort(names, numOfWords);
//print out names, sorted
//for(i=0; i<numOfWords; i++){
// printf("%s\n", names[i]);
//}
printf("What word would you like to search for? ");
scanf("%s", userWord);
//addName2Set(set1, userWord);
return 0;
}
Your initial
scanf()in a loop read everything up to EOF, so there’s nothing left for the ‘What word would you like to search for?’scanf()to read.One way around this problem is to read the initial names from a file (
fopen(),fscanf(),fclose()— and the file name might be an argument to the program, or a fixed name).Another way you could try is
clearerr(stdin);before the ‘What word’scanf(). That (clearerr()) unsets the EOF bit and allowsscanf()to try again. It may work if the input of the program is the terminal; it won’t help if the input of the program is coming from a file.This insists that you use
./a.out example.dat(instead of./a.out < example.dat). It will then work more or less as you want it to. Of course, the code for reading the file should be in a function that is passed the file name, the array, and the array size. The 320 in the loop is overflow protection and should be an enumerationenum { MAX_WORDS = 320 };that’s used both in the array declaration and the loop. The29is overflow protection; it is hard to parameterize that, but it is one less than the second dimension of the array.