简体   繁体   中英

Reading a text file into an array of integers

Given a file with some empty lines, some lines containing only integers, how would I make an array containing all of the integers? I have found methods for strings, but I need a list of integers. I want to do this using getline, but getline gives a string for "line"

A nonfunctioning example which returns the number of integers in the file and modifies a given array:

int getLinesFromFile(string fileName, int arr[], int arrLen) {
    ifstream userFile;
    userFile.open(fileName);
    if (userFile.is_open()) {
        int line;
        int arrCount = 0;
        while (getline(userFile, line)) {
            if (tline.length() != 0 && arrCount < arrLen) {
                arr[arrCount] = line;
                arrCount++;
            }
        }
        return arrCount;
    }

    else {
        return -1;
    }
    userFile.close();
}

You can just use the >> -operator to read values. It will ignore any whitespace, including empty lines, between values. Here is a modified version of your function that uses it:

int getLinesFromFile(std::string fileName, int arr[], int arrLen) {
    std::ifstream userFile(fileName);
    int count = 0;

    while(count < arrLen) {
            int value;
            userFile >> value;

            if (!userFile.good())
                    return -1;

            arr[count++] = value;
    }

    return count;
}

Note that you don't need to open and close the file manually, RAII will take care of that for you. Also, if the file could not be opened successfully, or if any other error occured while reading the file, userFile.good() will return false , so you can use that to detect and return an error. It's unclear if your function is supposed to read exactly arrLen values or if less is also valid. But at least you should take care not to write past the end of the provided array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM