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

2
  • Run in a debugger, step through the code line by line until you understand what's it's really doing. Commented Dec 14, 2014 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. Commented Dec 14, 2014 at 17:37

2 Answers 2

2

This line

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

index == num will be true always.

Sign up to request clarification or add additional context in comments.

1 Comment

The fix is to break out of the loop if the name is found.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.