Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C中获取数组中的值?_C_Function - Fatal编程技术网

如何在C中获取数组中的值?

如何在C中获取数组中的值?,c,function,C,Function,我希望结果显示为 Here is your name: John Here is your Date of birth: 02/02/1999 虽然数组中存在name、DOB,我成功地获取了name、DOB等的值,但问题是它给了我这个问题 Here is your name: John Here is your name: 02/02/1999 Here is your name: 442342352 意味着每个值只给我一个名称,尽管数组中存在所有内容 #include <stdio.

我希望结果显示为

Here is your name: John
Here is your Date of birth: 02/02/1999
虽然数组中存在name、DOB,我成功地获取了name、DOB等的值,但问题是它给了我这个问题

Here is your name: John
Here is your name: 02/02/1999
Here is your name: 442342352
意味着每个值只给我一个名称,尽管数组中存在所有内容

#include <stdio.h>
#include <stdlib.h>

int main(){
    const char listings[5][51] = {"Name", "Date of birth","ID card number","Phone number","Address"};
    FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
    char ch[100];
    int index = 0;
    for (int i=0; i<5; i++){
        if(fr != NULL){
            while((ch[index] = fgetc(fr)) != EOF){
                if(ch[index] == ' ') {
                    ch[index] = '\0';
                    printf("Here is your %s: %s\n",listings[i], ch);
                    index = 0;
                }
                else {
                    index++;
                }
            }
            fclose(fr);
        }
        else{
            printf("Unable to read file.");
        }
    }
    return 0;
}

你正在一次循环整个过程,你的“我”永远不会递增。然后,在while循环中增加它

while((ch[index] = fgetc(fr)) != EOF){
       if(ch[index] == ' ') {
           ch[index] = '\0';
           printf("Here is your %s: %s\n",listings[i], ch);
           index = 0;
           i++;
       }
       else {
             index++;
       }
   }

不要忘记删除for循环。

i是for int i=0的迭代变量;i<8;i++列表中的索引需要不同的变量。如果删除了for循环,那么我将如何输入i的值?只需使用while循环外的零对其进行初始化。不应关闭for循环内的文件。for循环应位于If fr!=空测试,而不是相反。