Ryan
Ryan

Reputation: 57

Read multiple strings from file

Having trouble figuring this out, trying to fscanf two names into two char[]

if (numpairs == 2){
            fscanf("%s %s", malename1[MAX], malename2[MAX]); //read in names 
            printf("%s %s", malename1[MAX], malename2[MAX]); //print out names

this is were it crashes and gives me "waring:warning: passing argument 1 of 'fscanf' from incompatible pointer type

EDIT: MAX is defined as 20, and malename1[MAX+1] malename2[MAX+1] (+1 to account for null)

EDIT: I've got the read in working somewhat, how can account for a space to end the read in of malename1? I'm reading in Chris for malename1 and Ryan for malename2 but for malename1 it scans ChrisRyan

Upvotes: 0

Views: 2552

Answers (2)

mohit
mohit

Reputation: 6074

If malename1 and malename2 are strings of type char *. Then the required statement should be:

fscanf(fp, "%s %s", malename1, malename2); //fp is file pointer

http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/

Upvotes: 0

hmjd
hmjd

Reputation: 122011

The first argument to fscanf() is a FILE*, not a char*.

Assuming you meant to use scanf(), the code is attempting to treat a char as a char[] (assuming malename1 and malename2 have type char[], as stated). Change to:

scanf("%s %s", malename1, malename2);
printf("%s %s", malename1, malename2);

or if fscanf():

fscanf(fp, "%s %s", malename1, malename2); /* where 'fp' is a valid 'FILE*'. */

Note you could also add a maximum length to be read to prevent buffer overruns:

fscanf(fp, "%20s %20s", malename1, malename2); /* Read max of 20 chars. */

Upvotes: 1

Related Questions