Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

c - Incorrect output using strcmp

I'm doing the day 8 of the 30 days of code in HackerRank and I am having a problem with strcmp. The code asks the user for names of people and their numbers, then asks for other names, if a name wasn't entered before, then it outputs Not found, but if it was then it outputs the name and his number. But for some reason, the output only works in the last loop of the for statement. Code:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct {
    char name[100];
    int number;
} phonebook;

int main() {
    int n = 0;
    do {
        scanf("%i", &n);
    } while (n < 1 || n > 100000);
    
    int i = 0;
    phonebook people[n];
    
    for (i = 0; i < n; i++) {
        scanf("%s %i", people[i].name, &people[i].number);
    }
    
    char othernames[n][100];
    
    for (i = 0; i < n; i++) {
        scanf("%s", othernames[i]);
    }
    
    for (i = 0; i < n; i++) {
        if (strcmp(othernames[i], people[i].name) == 0) {
            printf("%s=%i
", people[i].name, people[i].number);
        } else {
            printf("Not found
");
        }
    }
    return 0;
}
question from:https://stackoverflow.com/questions/65860616/incorrect-output-using-strcmp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You didn't find the othernames from the beginning to end to compare peopleevery time, so you need to replace

for (i = 0; i < n; i++) {
  if (strcmp(othernames[i], people[i].name) == 0) {
    printf("%s=%i
", people[i].name, people[i].number);
  } 
  else {
    printf("Not found
");
  }
}

to

bool found = false;
for (i = 0; i < n; i++) {
  for ( j = 0 ; j < n ; j++ ) {
    if (strcmp(othernames[j], people[i].name) == 0) {
      printf("%s=%i
", people[i].name, people[i].number);
      found = true;
    } 
  }
}

if ( found == false ) printf("Not found
");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...