简体   繁体   中英

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

This line

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

index == num will be true always.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM