3

Compare the data of an array of strings in c

 2 years ago
source link: https://www.codesd.com/item/compare-the-data-of-an-array-of-strings-in-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Compare the data of an array of strings in c

advertisements

I'm trying to compare something that i read with fgets with the words from the first column of the array, but I can't get it, I thing it could be the \0 at the end of each string but I can't get the comparison works

#include <stdio.h>
#include <string.h>
#define MAX_STRLEN 3  

const char *bdato [][columns]={
    {"tc","Torta Cubana"},
    {"th","Torta Huatulco"},
    {"tm","Torta Mexicana"},
    {"tr","Torta Rusa"},
    {"r", "Refresco"},
    {"a", "Agua sabor"}};

int total() {
    char v[20];
    int flag=0,cont=0;
    fgets(v,sizeof(v),stdin);
    do {
        if(strcmp(v,bdato[cont][0])==0){ /*this*/
            flag=1;
            printf("I found one");
        }
        cont++;
    } while(!(flag==1||cont==5));
}

the rewritten code:

  #defines .....
  .............
  .............
 int total(){
 size_t len = strlen(v);
        printf("something here");
        fgets(v,sizeof(v),stdin);
        len = strlen(v);
        if(len>0){
        v[len - 1] = '\0';}
        if(strcmp((v,bdato[cont][0])==0)){
            /*another code*/
        }
 }


Your string comparisons are failing because fgets() includes the newline that ends the input line.

You need to strip that out, something like

const size_t len = strlen(v);
if(len > 0)
  v[len - 1] = '\0';

should do it. The if is just to be somewhat sure we're not about to index backwards.

Also, you should check that fgets() succeeds before relying on v to have valid input.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK