如何使用fscanf将字符串放入数组中? 我正在使用FSCANF从文件中读取,我正在尝试将这些字符串放入数组中。它似乎有效,但我只将最后一个字符串放入我的数组中。当我尝试打印它时,我只打印

问题描述 投票:0回答:2
如果有人感到困惑。另外,我的cmdline文件具有以下字符串。

输出为:

foo barr tar 526-4567 456-8792
ETC...
456-8792
56-8792
6-8792

在这里是代码:

2

int main (int argC, char *argV[]) {
    FILE *fp;
    int index;
    int ret;
    char str[1000];

    //Need at least 2 files to begin program
    if (argC < 3) {
        fprintf(stderr, "Usage: %s file\n", argV[0]);
        exit(1);
    }//if statemtn

    //check to see if the CMDLINE file is in the arguments
    ret = scanC(argC, argV);

    //if no CMDLINE file is found, print error and exit
    if (ret == 1) {
        fprintf(stderr, "you must provide a CMDLINE file\n");
        exit(1);
    }

    //iterate and open CMDLINE file and read from it
    for (index = 0; index < argC; index++) {
        if (strcmp(argV[index], "CMDLINE") == 0) {
            fp = fopen(argV[index], "r");
            //error check
            if (fp == NULL) {
                fprintf(stderr, "Counld not open file %s\n", argV[index]);
                exit(1);
            }//if statment

            //read from fscanf and put it's arguments into an array
            while (!feof(fp)) {
                char *p2 = str;
                //scan the strings of the file into str array
                while (fscanf(fp, "%s", p2) != EOF) {
                    p2++;
                }//while loop 2
            }//while lop 1

            //close the file for it is not needed to be open anymore
            fclose(fp);
        }//if statement
    }//for looop

    char *p;
    p = str;
    int j;
    for (j = 0; j < strlen(str); j++) {
        printf("%s\n", p);
        p++;
    }
    return 1;
}

您有一个字符串,示例

char *p; p = str; int j; for (j = 0; j < strlen(str); j++) { printf("%s\n", p); p++; }
,您可以将其打印为
"abcd"
c arrays file pointers scanf
2个回答
2
投票
printf("%s\n", str);

也许您在“字符数组”和“字符串数组”

中感到困惑

abcd bcd cd d

在现实世界的应用程序中,您使用
//This will reserve 100 character arrays, or 100 strings char *arr[100]; int count = 0; while (fscanf(fp, "%999s", str) == 1) { arr[count] = malloc(strlen(str) + 1); strcpy(arr[count], str); count++; if (count == 100) break; } int i; for (i = 0; i < count; i++) printf("%s\n", arr[i]);

malloc
分配足够大的字符串以读取文件。
    

您可以使用标记设置“当前字符”:

realloc
这将使整个文件存储在您的字符串中 
只要它不到1000个字符!
否则,只需在时循环中添加一个保障。
    


1
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.