user2986673
user2986673

Reputation: 171

find string in the array - c programming

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??

Upvotes: 0

Views: 105

Answers (2)

Michael Tiemann
Michael Tiemann

Reputation: 281

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.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

This line

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

index == num will be true always.

Upvotes: 2

Related Questions