简体   繁体   中英

Strings not being read correctly from file using fscanf

I'm using fscanf to take input of a specific format. The line I'm trying to read is:

ABCDEFGHIJK x

My fscanf code looks like:

fscanf(circuit, "%s %s %s %s %s %s %s %s %s %s %s %c ",
       str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11, &a);

In this example "circuit" is the name of the file. For some reason, "K" and 'x' get read correctly (as str11 and a respectively), but the rest of the characters do not get read correctly. The reason I've opted for the string identifier vs the char identifier is because the line may potentially contain single digit integers. In the case of an integer I just convert the string to an integer in a later code block. Why isn't this working correctly?

I have this code working on my machine.

#include <stdio.h>
#include <stdlib.h>

//#define _CRT_SECURE_NO_WARNINGS

int main()
{
    char str1[2], str2[2], str3[2], str4[2], str5[2], str6[2], str7[2], str8[2], str9[2], str10[2], str11[2];
    char a;
    FILE * fp;
    fp = fopen("test.txt", "w+");
    fputs("A B C D E F G H I J K x", fp);

    rewind(fp);
    fscanf(fp, "%s %s %s %s %s %s %s %s %s %s %s %c ", str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11, &a);

    printf("Read String1 |%s|\n", str1);
    printf("Read String2 |%s|\n", str2);
    printf("Read String3 |%s|\n", str3);
    printf("Read Character |%c|\n", a);

    fclose(fp);

    return(0);
}

Output :

Read String1 |A|
Read String2 |B|
Read String3 |C|
Read Character |x|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM