ignoring problem in C++

This is just the portion of my program. This program displays Not Found even if the id number is found.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void search(void)
{
    char ID[10];
    int i, found;

    cout<<"Enter ID to search: ";
    gets(ID);
    found=0;
    for(i=0;i<top;i++)
    {
        if(!strcmp(ID, info[i].ID))
        {
            display(i);
            found=1;
            cout<<"\n";
        }
        else
        {
            cout<<"Not found\n";
        }
    }
}


here's the incorrect output

1
2
3
4
5
6
7
Enter ID to search: 111

Not found
Name: jude
ID: 111
Semester: 1
Major: IT


I just want to remove the "Not found"
Last edited on
Your snipped is not complete, so it's hard to follow your operations.
I suppose info is an array to search for and top an index to loop
through this array.

If it so, your search checks each entry and compares the input value
with the actual array entry. If this compare doesn't match, the else
condition is executed.

So if you want this output only if no match occurs, move this behind
your loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void search(void)
{
    char ID[10];
 
    cout<<"Enter ID to search: ";
    gets(ID);
    
    bool match = false;
    for(int i=0;i<top;i++)
    {
        if(!strcmp(ID, info[i].ID))
        {
            display(i);
            cout<<"\n";

            match = true; // report success
            break;  // stop continue loop on match
        }
    }

    if(!match) {
            cout<<"Not found\n";
    }
}


You should change multiple things in your code. Use an STL container instead of the array, to be more safe. Also use std::string and the compare function to check the input result. I've removed the found variable, it makes no sense for me.
Last edited on
Topic archived. No new replies allowed.