【问题标题】:How can i read a string from a file which is before a integer如何从整数之前的文件中读取字符串
【发布时间】:2018-12-28 15:04:07
【问题描述】:

我有这个文本文件:

2 6
99 100 14 15 1 4 29 43 15 15
31 24 2 0 2 0 2 0 12 12
1 5 2 6 3 50 2 0 1 100
31 24 2 0 2 0 2 0 12 12
99 100 14 15 1 4 29 43 15 15
Lucky 0 0 100 100
James 2 0 100 100
Jerry 2 4 100 100
Cristofor 0 2 100 100
Chris 2 3 100 100
Miclaus 2 1 100 100

我想读取多个结构中的所有数据。 这是我的代码:我阅读了前 6 行,我想阅读接下来的 6 行并将每个单词放入变量中。我不知道怎么读那个字符串。

void citireDate(){
char c;
FILE *f;
f = fopen("nume.in","r");
fscanf(f,"%d", &R);
fscanf(f,"%d", &P);
for(int i=1;i <= 2*R+1 ; i++)
    for(int j=1;j <= 2*R+1; j++){
        fscanf(f,"%d",&ghetar[i][j].inaltime);
        fscanf(f,"%d",&ghetar[i][j].manusi);
}

for(int i=1;i<=6;i++){

//here i have to read that string
    fscanf(f,"%d",&spiridusi[i].x);
    fscanf(f,"%d",&spiridusi[i].y);
    fscanf(f,"%d",&spiridusi[i].hp);
    fscanf(f,"%d",&spiridusi[i].stamina);

}


fclose(f);
}

我怎样才能读到那个字符串?

【问题讨论】:

    标签: c string file


    【解决方案1】:

    一口气读完所有行fscanf(f, "%s %d %d %d %d\n", ...);

    for(int i=1;i<=6;i++) {
      fscanf(f, "%s %d %d %d %d\n",
             &spiridusi[i].?????,
             &spiridusi[i].x,
             &spiridusi[i].y,
             &spiridusi[i].hp,
             &spiridusi[i].stamina);
    }
    

    或者当然我想在4个整数之前的字符串中没有空格

    奇怪的是第一个索引总是 1,我认为它们在所有 for 中都必须是 0(除非你有充分的理由从 1 开始)

    【讨论】:

    • 啊,好的,警告向量/数组中的第一个索引是 0 而不是 1,你在 for 中从 1 开始
    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2018-10-25
    • 2017-05-03
    • 2019-06-21
    相关资源
    最近更新 更多