c - 如何使用 fscanf 将字符串放入数组?

标签 c arrays file pointers scanf

所以我正在使用 fscanf 从文件中读取,并且我正在尝试将这些字符串放入一个数组中。它似乎有效,但我只是将最后一个字符串放入我的数组中。当我尝试打印它时,我只打印最后一个字符串的字符。我没有包括我的方法,因为它不会影响 fscanf 的功能,以防有人感到困惑。此外,我的 CMDLINE 文件包含以下字符串 foo barr tar 526-4567 456-8792

输出是:

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 arguements
    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 arguements 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",您可以将其打印为 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]);

在实际应用程序中,您使用 mallocrealloc 来分配足够大的字符串数组以读取文件。

关于c - 如何使用 fscanf 将字符串放入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40390556/

相关文章:

c - 在 8 位 PIN 中设置一位而不更改其他位

c - Linux 上的磁盘 IO 模拟器

python - 从 python 中运行 python 脚本并捕获异常

python - Flask.Response 在网络浏览器中无法开始下载

c - 在没有包含防护的情况下避免重新声明错误

c - 使用 Infinity 和 NaN 禁用异常

将值从一个数组复制到另一个数组

cocoa - 使用 xCode 制作图表

.net - 带双括号 ()() 的 VB.NET 数组

java - 动态更改Windows保存目录?