使用fscanf()从文件输入的奇怪输入

时间:2017-04-03 18:46:30

标签: c arrays pointers scanf

我的主要目标是利用fscanf()从文件中接收每个单词并将其存储到数组位置。按照目前的情况,我遍历文件,将每个单词设置为wordList[]中的某个位置。我可以在将值放入数组时打印出来,并且每个值都可以正确放置。但是在循环之后,当我尝试只打印其中一个值时(简单地检查一切都按原样进行),我得到了一个奇怪的输出。打印wordList[5]中包含的字符串时,它会在位置[5]之后打印每个单词的第一个字符,并打印收集的最后一个单词。

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

void readFile (FILE *fPtr, char *fileName) {
    FILE *newFilePtr;
    char wordList[1000];
    int i = 0;

    newFilePtr = fopen(strcat(fileName, ".out"), "w");          // Blank document created under same file name, but with ".out"

    while(fscanf(fPtr, "%s", &wordList[i]) == 1) {              // Read in strings from main file into wordList
        printf("%s\n", &wordList[i]);
        ++i;

        if (i > 10)                                             // KEEP OUTPUT SHORT FOR STACK OVERFLOW QUESTION
            break;
    }
    printf("%s\n", &wordList[5]);                     // PRINTS WILD VALUE AT POSITION 5
    fclose(newFilePtr);
}
int main (int argc, char *argv[]) {
    int lineSize;
    char *fileName = argv[2];                                   // Store name of file for future operations
    FILE *fPtr;

    if (argc != 3) {
        fprintf(stderr, "%s", "ERROR: Incorrect arguments. Please input a line size and a file.\n");
        return;
    }

    lineSize = atol(argv[1]);                                   // Convert string to it's integer equivalent

    if (lineSize < 25 || lineSize > 100) {
        fprintf(stderr, "%s", "ERROR: Line size not within range.\n");
        return;
    }

    if (fPtr = fopen(fileName, "r")) {                          // If the file exists, open it for reading
        readFile(fPtr, fileName);
        puts("FILE OPENED SUCCESS");
        fclose(fPtr);
    } else {
        fprintf(stderr, "%s", "ERROR: File could not be opened.\n");
        return;
    }
    return;
}

我的当前输出(仅限于前10个值以保持简短):

Mason–Dixon Line (or Mason and Dixon's Line) was surveyed between 1763 DLwsb1763 // Should print "Dixon's" (the string at location 5) FILE OPENED SUCCESS

line 11创建新文件,以便在格式化文件时使用。目前,我只关心正确扫描原始文件中的值。

0 个答案:

没有答案