2

I want to fprintf() 3 strings to a file, all on the same line.

The first two cannot contain spaces while the 3rd may. I.E. word word rest of line

Can some one tell me how to fscanf() that into 3 variables?

I don't mind putting some delimiters if it makes it easier. E.G. [word] [word] [rest of line]

xaizek
  • 5,098
  • 1
  • 34
  • 60
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551

2 Answers2

4

You can do it without delimiters, too:

char s1[32], s2[32], s3[256];

if(sscanf(line, "%31s %31s %255[^\n]", S1, S2, S3) == 3)
 /* ... */

This should work, as long as the input line actually does end with a newline.

Of course, you should adjust the string sizes to fit. Also you can get trickery with the preprocessor to avoid repeating the sizes, but doing so makes it more complicated so I avoided that for this example.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

You could use scanf to scan two words, then use fgets to get the rest of the line.

FILE *f = stdin; // or use fopen to open a saved file

// use buffers large enough for your needs
char word1[20];
char word2[20];
char restOfLine[100];

// make sure fscanf returns 2 (indicating 2 items scanned successfully)
fscanf(f, "%20s %20s", word1, word2); 

// make sure fgets returns &restOfLine[0]
fgets(restOfLine, sizeof restOfLine, f);

Note that if fgets encounters a '\n' character, it is put into the buffer as well, so if you don't want it, you'll have to strip it out manually. If fscanf returns something other than 2, or fgets returns NULL, then there was a problem reading your input.

dreamlax
  • 93,976
  • 29
  • 161
  • 209