【问题标题】:using 2 fscanf consecutively连续使用 2 fscanf
【发布时间】:2019-06-10 16:01:23
【问题描述】:

我想从 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);

我需要连续使用fscanfs 的代码(用于大学)的 sn-p 是:

                   ......
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);

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

【问题讨论】:

  • 另外,使用*scanf()而不检查返回值...
  • 你的字符串太小 - 你没有给终结者留出空间。
  • @paulR,谢谢你的回答,使用fscanf时如何查看“最小字符串长度”?
  • @All.in C 中的字符串只不过是 null 终止的字符数组。数组的大小应至少比字符串的长度大一倍,以容纳所有字符以及 null 字符。

标签: c scanf


【解决方案1】:

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

工作代码:

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;

}

【讨论】:

  • 如果用户改变了输入怎么办? fscanf 的文档指定“指定最大字段宽度的可选非零十进制整数”。建议fscanf(fp, "%2s", xxx)?
猜你喜欢
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
相关资源
最近更新 更多