0

so I'm trying to get a string from a file that is in quotation marks and has a space between the two words so something like this "john doe" and I'm trying to save it into a single string variable, but instead, fscanf only saves the first word, I was wondering how can I save both words into one variable instead of 2

data.txt

"john doe"

main.c

FILE * infile = fopen("data.txt","r");
    if(infile == NULL){
        printf("error");
        return -1;
    }
char username[20];
fscanf(infile, "%s", username);
Mas_T
  • 13
  • 3

1 Answers1

1

I was wondering how can I save both words into one variable instead of 2

fscanf(infile, "%s", username); only saves non-white-space input.

Read a line of file input with fgets(). Notes that names can be quite long.

#define NAME_SIZE 64     // Longest _expected_ name size

char username[NAME_SIZE * 2]; // Use a generous buffer
if (fgets(username, sizeof username, infile)) {
  // Look for "name"
  char *start = strchr(username, '\"');
  char *end = start ? strchr(start + 1, '\"') : NULL;
  if (end)  {
    printf("Username:<%.*s>\n", (int) (end - start - 1), start);

    // Additional code perhaps to:
    // trim spaces
    // Validate a length limit
    // Check character set - I'd accept at least A-Z, A-z, -, ', ., space, etc.
  }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • would something like this fscanf(infile, " \"%[^\"]\" ", username) also work, or is there something wrong with this method? – Mas_T Jun 09 '20 at 19:43
  • @Mas_T `fscanf(infile, " \"%[^\"]\" ", username) ` works almost OK when input is well formed - something robust code does not assume. `fscanf(infile, " \"%[^\"]\" ", username) ` can read more than the end of line, may read more than one line when leading lines are only whitespace, is as bad as [gets](https://stackoverflow.com/q/1694036/2410359) - it lacks a width limit. It is also difficult to recover from errant input. Is quite bad if only 1 `'\"'` exist. Your call. – chux - Reinstate Monica Jun 09 '20 at 19:47