Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

c - Assigning variables from a string problem

I'm trying to assign 'hp' , 'd', 's', 'status' respectively from an input file which has the content '600 144 100 Rain' . I have sucessfully assigned 3 of the numbers to hp,d,s ,but the 'Rain' string remains undone since it appeared blank screen everytime I try adding it in. Here is my C code :

#include <stdio.h>

int read_file(int *hp, int *d, int *s, char t[]) {
    FILE *infile, *outfile;

    infile = fopen("input1.inp", "r");
    // input1.inp's content is "600 144 100 Rain"
    
    fscanf(infile, "%d %d %d %s", &hp, &d, &s, t); 
    
    printf("hp = %d
",hp ) ;
    printf("d = %d
",d ) ;
    printf("s = %d
",s ) ;
    printf("status = %s", t) ;


    fclose(infile); 
    return 0;
}

If I odd the 'Rain' string out then my code run perfectly. Can someone show me how to do it properly, what mistake did I make ?

Please notice that declaring variables in the parameter area is compulsory for me , I need it to pass the variables to the main part . Thank you !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are invoking undefined behavior by passind data having wrong type to fscanf() and printf(). Be careful because hp, d and s are pointers.

The part

    fscanf(infile, "%d %d %d %s", &hp, &d, &s, t); 
    
    printf("hp = %d
",hp ) ;
    printf("d = %d
",d ) ;
    printf("s = %d
",s ) ;

should be

    fscanf(infile, "%d %d %d %s", hp, d, s, t); 
    
    printf("hp = %d
",*hp ) ;
    printf("d = %d
",*d ) ;
    printf("s = %d
",*s ) ;

Also the results of fopen() and fscanf() should be checked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...