c - 连续使用 2 个 fscanf

标签 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);

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

最佳答案

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

工作代码:

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;

}

关于c - 连续使用 2 个 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529783/

相关文章:

objective-c - Objective C 中的 Scanf 导致 Xcode 和程序崩溃

c - 理解 scanf 语法

c - 写入和读取二进制文件

c - calloc 和 malloc 后跟 memset 有什么区别?

c - 如何扫描文件中的某些字符

c - scanf() 将换行符保留在缓冲区中

c++ - 使用 fscanf 读取双倍

c - libssh 服务器无法导入私有(private) RSA 主机 key

c - 通过调用函数打印 C 中数字范围的值

c++ - 需要管理一 block 'theoretical'内存的slab