连续使用2 fscanf

时间:2019-06-10 16:01:23

标签: c scanf

我想从C中的以下文件中读取内容:

示例 file.txt

ab cd efg mnop

1234 123 12 21

我想读取并在各个变量中存储用空格分隔的单词。 我知道我可以使用:

fscanf(fp, "%s %s %s.....", var1, var2, varN);

但是,我的代码(大学)不需要fscanf(fp, "%s %s %s.....", var1,var2,varN);

我需要连续使用fscanf的一段代码(用于大学)是:

                   ......
while(!feof(fp)) {
    fscanf(fp,"%2s",posRobot);

    if(!strcmp(posRobot, "R1") == 0){
        fscanf(fp, "%4s", pos_temp);
            posR1_temp=0;
                   .......

但是它没有按预期工作。我寻求帮助的代码:

int main()
{
    FILE *fp;
    char var1[2];
    char var2[2];
    char var2[3];
    char var2[4];
    ....


    fp = fopen("file.txt", "r");
    if(fp == NULL) {
        printf("Error opening file!"); 
        exit(0);    
    }

    //now using fscanf, trying to read the first two characters.
    fscanf(fp,"%s",var1);

    //test to see if i read it successfully
    printf("\n1st 'fscanf' : %2s",var1);

    //now using fscanf again, to read the next string.
    fscanf(fp,"%s",var2);

    //test to see if i read it successfully
    printf("\n1st 'fscanf' : %2s",var2);

错误:编译成功,但在输出窗口上未显示任何内容。

1 个答案:

答案 0 :(得分:0)

非常感谢你们,非常快速的答复。 问题是我没有为“空字符”分配另一个“空间”

工作代码:

int main()
{
FILE *fp;
char xxx[3];
char bb[3];
char cc[4];
char aa[5];
char hh[4];

fp=fopen("fscanf.txt", "r");
if(fp==NULL){
    printf("Error opening file!"); 
    exit(0);    
    }


fscanf(fp,"%s",xxx);
printf("\n1st 'fscanf' : %3s",xxx);

fscanf(fp,"%s",bb);
printf("\n2nd 'fscanf' : %3s",bb);

fscanf(fp,"%s",cc);
printf("\n3rd 'fscanf' : %4s",cc);

fscanf(fp,"%s",aa);
printf("\n4th 'fscanf' : %5s",aa);

fscanf(fp,"%s",hh);
printf("\n5th 'fscanf' : %4s",cc);

return 0;

}