我正在尝试从制表符分隔的文本文件中获取数据。但我无法得到结果

时间:2017-11-20 02:45:40

标签: c pointers

这是我的代码

#include <stdio.h>
#include <string.h>

main() {

    FILE *fp;
    char buff[1024];
    char q1[6];
    char q2[6];
    char * pch;
    int i;

    fp = fopen("QFile.txt", "r");
    fgets(buff, 255, (FILE*)fp);
    pch = strtok (buff,"\t");
    int count=0;
    while (pch != NULL)
    {
        q1[0]=("%s",*pch);
        pch = strtok (NULL, "\t");
    }

    fgets(buff, 255, (FILE*)fp);
    pch = strtok (buff,"\t");
    count=0;
    while (pch != NULL)
    {
        q2[0]=("%s",*pch);
        pch = strtok (NULL, "\t");
    }
    for(i=0;i<6;i++)
        printf ("%s\n",q1[i]);

    for(i=0;i<6;i++)
        printf ("%s\n",q2[i]);

    fclose(fp);
}

这是我的QFile.txt看起来像:

1   20 % of 2 is equal to   1)1 2)0.4   3)0.5   2
2   If Logx (1 / 8) = - 3 / 2, then x is equal to   1)-4    2)4 3)1/4   2

当我正在编译时,它会显示一些警告:

test3.c:4:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 main() {
 ^

test3.c: In function ‘main’:
test3.c:32:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
  printf ("%s\n",q1[i]);
          ^

test3.c:35:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
  printf ("%s\n",q2[i]);
          ^

我无法弄清楚如何纠正这个问题。我想向两个阵列提出两个mcq问题。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

test3.c:4:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main() {
^

main()默认返回 int 。写

int main() { 

并返回一个int,0告诉来电者一切正常

   return 0; // final line of main
}

test3.c: In function ‘main’:
test3.c:32:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
  printf ("%s\n",q1[i]);
      ^

test3.c:35:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
  printf ("%s\n",q2[i]);
          ^

q1q2是char数组,因此qx[y]给出了这些数组的第(y + 1)个元素,即char。

如果您确实要在i位置打印字符,请使用%c(字符转换为int,因此警告int

  printf ("%c\n",q1[i]);
  printf ("%c\n",q2[i]);