【问题标题】:How to read in both Strings and Ints from a file, on seperate lines如何在单独的行中从文件中读取字符串和整数
【发布时间】:2012-01-23 04:52:07
【问题描述】:

所以我一直在搜索你的网站,但我仍然不清楚如何做到这一点,所以让我尽我所能解释一下。

我有一个像这样的输入文件:

2
Joe Flacco
1 3 5 6 7 8
Tom Brady
7 9 10 15 52 53

第一个数字是文件中“人”的数量,接下来是他们的名字和姓氏。接下来是 [0,53] 之间的 6 个整数,它们是他们的“彩票”号码。无论如何,我可以让我的代码提取第一个数字,但要获得他们的姓名和数字证明很难。

最后一部分,是让它适合我们声明的结构(我们必须使用它,它包含变量 firstName[20] lastName[20] 和 numbers[6]。我知道我在如何正确地做这一切,但我发布我的代码,所以你们可以看到我在做什么。我感谢任何和所有的帮助。另外,我试图学习如何去做,而不是让你为我正确的程序,所以任何非常欢迎解释。

for(int i=0; i < numPlays;i++)
{   
        char firstName[20];
        char lastName[20];
        for(int x=0; x<3;x++)
       fscanf(fr, "%c", &firstName[x]);
       for(int x=0; x<6;x++)
       fscanf(fr, "%c", lastName[x]);   
        for(int g=0; g<6; g++)
        {
        fscanf(fr, "%d", &Steve.numbers[g]);
        }
        temp[i]= Steve;
            //Tester code, lets hope this works
        for(int x=0; x<3;x++)
        printf("The persons name is %c.\n",&firstName[x]);
        //printf("The persons last name is %c.\n",temp[i].lastName);
}

【问题讨论】:

  • 对于初学者,您需要使用"%s" 来读取字符串,使用fscanf 而不是逐个字符读取,即fscanf(fr, "%s", lastName);(注意没有&amp; 或@ 987654328@ & 没有for 循环)。但使用fgets 更安全。同样在printf 打印字符使用"%c",但不要传递地址,即printf("The persons name is %c.\n",firstName[x]); 或更好地直接打印字符串printf("The persons name is %s.\n",firstName);(不带for 循环)。 NUL C 中 strings 的终止是必须的

标签: c arrays char int


【解决方案1】:

使用 fgets strtokatoi 可以满足您的需求。至于你的程序结构,你可能想要这样的东西:

typedef struct Player {
    char name[20];
    int numbers[6];
} Player;
#define SIZE(x) (sizeof(x)/sizeof(*(x)))

Player readplayer(){
      Player p;
      int x;
      char * num;
      //read a line with fgets;
      //memcpy() to p.name;
      //read another line
      for(num=strtok(line, " "),x=0;x<SIZE(p.numbers);x++, num=strtok(NULL," "))
          p.numbers[x] = atoi(num);
      return p;     
}

int main()
{
     //read a line with fgets
     int x, nplayers = atoi(line);
     Player *players = malloc(nplayers*sizeof(Player));
     for(x=0;x<nplayers;x++)
         players[x] = readplayer();
}

【讨论】:

  • 我真的很感激戴夫,但我很困惑的一件事是,你把两个名字(名字和姓氏)放在一起了吗?给我的结构必须有两个不同的变量。这是给我的实际结构。 typedef struct KnightsBallLottoPlayer { char firstName[20];字符姓氏[20];整数[6]; } KBLottoPlayer;
  • 我把两个名字放在一起,但是分开它们应该是微不足道的。 Strtok 将一行拆分为子字符串,所以我说memcpy to p.name,只是strtok the line, memcpy to p.first. strtok again, and memcpy to p.last
【解决方案2】:

您可以为此目的使用 fgets() 函数。它会将行读取为字符串。将数字读取为字符串后,只需将其转换为整数即可。

【讨论】:

  • 但我如何将“整数字符串”分成 6 个不同的数字。稍后我必须将它们与 6 个随机生成的中奖号码进行比较。
  • 好吧,您需要将所有单词/数字分开,然后将数字转换为 int,您就可以做到。转换时,您需要使用 isNum() 方法检查数字。如果返回 true,则将其转换为 int。
【解决方案3】:

您可以将读取文件和解析内容分开,即定义 readline() 并独立解析每一行 example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2020-02-10
    • 2023-04-09
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多