0

write a C program that read data from file data.in and store in an array.

a) find the name entered from keyboard. If no match then return "Not found"

b) list all names that are not duplicate in array

data.in file content:

5

Bill Gates

Steve Jobs

Daniel Rhode

Billy Carpenter

Steve Jobs

when i typed in the name, the output was always not found even when matched. What is the problem here??

user2986673
  • 161
  • 11
  • Run in a debugger, step through the code line by line until you understand what's it's *really* doing. – Some programmer dude Dec 14 '14 at 17:35
  • 2
    You read the names from the file with `fgets`, which leaves the newline at the end of the string. But you read the name to search for with `gets`, which does not leave the newline. One fix is to use `fgets` to read the name to search for. – ooga Dec 14 '14 at 17:37

2 Answers2

2

This line

if(index == num)
   printf("\n%s Not Found in array",name);

index == num will be true always.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1

The problem is that the fgets that reads from the file data.in includes the trailing newline on each line, whereas the gets from stdin does not include the trailing newline. That is why there is no match.

You can read more about the trailing newline problem here: Removing trailing newline character from fgets() input

And, as others have pointed out, you need to break from the loop when you find a match.

Community
  • 1
  • 1
Michael Tiemann
  • 251
  • 2
  • 9