【问题标题】:printing and scanning files in c在c中打印和扫描文件
【发布时间】:2013-11-30 02:30:25
【问题描述】:

我正在用 c 语言编写一个包含名称和数字文件的程序。用户输入一个数字,然后它应该打印出它旁边的名字。该文件看起来像这样......

154 Sam
245 Jane
345 Joe

我不确定如何在匹配用户输入后只打印文件中的某些单词,但我知道当我使用 fgets 和 fscanf 时它会打印整个文件

到目前为止我有

FILE *pf;
pf = fopen("C:\\Sample.text", "a+");
char str[200];
char input2[10];
printf("\nPlease enter a number:");
scanf("%s", &input2);`

while(!feof(pf))
{
    fscanf(pf,"%s/n",str);

    if (strcmp(str,input2)==0)
    {
        printf("The First name is %s\n",fgets(str,10,pf));
    }
}

【问题讨论】:

    标签: c file fgets scanf


    【解决方案1】:

    有多种方法可以将一条线分成几部分,以便您可以单独处理它们,但由于您已经在使用scanffscanf,您可能需要考虑sscanf。假设您已将文件中的一整行读入str,并且该行同时包含一个数字和一个名称:

    sscanf(str, "%s %s", number_str, name_str);
    

    会将第一个单词读入number_str,将第二个单词读入name_str

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多