7 years, 2 months ago.

I need help with strings

Hello, I'm new to nucleo boards and I'm having a problem with nucleo f401re

int readPassword(string pass[]) { FILE *fp; string fString[20]; fp = fopen("/sd/password.txt","r"); while(!feof(fp)){ fscanf(fp,"%s\n",fString); if(strcmp(fString,pass) == 0){ fclose(fp); return 0; } } fclose(fp); return -1; }

it gives me this:

Warning: Argument is incompatible with corresponding format string conversion in "main.cpp", Line: 19, Col: 27 Error: Argument of type "std::string *" is incompatible with parameter of type "const char *" in "main.cpp", Line: 20, Col: 20

Can anyone explain me why? Thanks

In the future please use

<<code>>
your code
<</code>>

when posting code so that the formatting is preserved.

int readPassword(string pass[]) {
  FILE *fp;
  string fString[20];
  fp = fopen("/sd/password.txt","r");
  while(!feof(fp)){ 
     fscanf(fp,"%s\n",fString);
     if(strcmp(fString,pass) == 0){ 
       fclose(fp);
       return 0;
    }
   }
   fclose(fp);
   return -1;
 }
posted by Andy A 27 Jan 2017

1 Answer

7 years, 2 months ago.

The issue is that you are being inconsistent between c style strings which are char arrays and c++ std:string types.

A string can either be stored in a char[] or a std:string (not a std:string[]). When going between the two you need to use the correct conversions, they aren't the same thing.

Generally unless you're doing some complex string manipulation for an resource limited system like mbed it's best to stick to c style char arrays.

int readPassword(char pass[]) { // It would be more normal to char *pass here but both will work.
  FILE *fp;
  char fString[20];
  fp = fopen("/sd/password.txt","r");
  while(!feof(fp)){ 
     fscanf(fp,"%s\n",fString);  // should really be %19s rather than %s
     if(strcmp(fString,pass) == 0){ 
       fclose(fp);
       return 0;
    }
   }
   fclose(fp);
   return -1;
 }

The %19s is to prevent a buffer overflow bug, one of the most commonly exploited security holes in software. Without it if someone entered a string that was 100 characters long the code would still try to place the values in fString, the end result is that whatever happened to be stored in memory in the locations immediately after fString would be replaced with whatever was in the input file. By careful manipulation of what is written there it is sometimes possible to take control of the system. Probably not much of an issue in this case but a good habit to have. By putting %19s you are telling the program to read a maximum of 19 characters, one less than we have space to store because we need to ensure we still have space for the 0 that c adds to indicate the end of a string.

Accepted Answer