简体   繁体   中英

Read integers from text file and store them into an array

I am pretty much new to C++ and got this assignment from school to do and now I am stuck as I can't get it to work, some help would be appreciated. Thanks in advance.

I have a text file with integers like this: 8 3 7 1 2 0

I need to create program which reads those integers and stores them in an array. Program checks text file and counts how many integers are there and accordingly creates array of size that is needed then it fills that array with integers from the file. I've came up with something like this:

#include <iostream>
#include <fstream>
using namespace std;

int main(){

    ifstream File("data.txt");
    int count;
    File >> count;
    int array[count];
    for(int i=0; i<count; i++){
        File >> array[i];
    }

    cout<<"File contains: "<<count<<" integers";
    cout<<"Array of integers taken from the file: ";

    for(int i=0; i<count; i++){
        cout<<array[i];
    }
}

For some reasons my count integer doesn't get any value, I've checked and it's just a zero after program and thus my whole code won't work.

Variable lenght array does't exist un c++. Use a vector<int> to store the data.

Btw, you can use:

System("pwd");//linux

To check working path.

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() is written and failbit flag is set.

This comes from the documentation of operator>> of std::ifstream . As you can see, if extraction fails, then the variable is set to 0 . Why did extraction fail? Well, you never check if the file is open or not, so it is possible that the file doesn't exist and loading it failed.

But even if your file is loaded correctly, it doesn't seem to me that the first element in the file is the amount of integers in it. If it is not, you will have to read each integer, and store them in a dynamic array, as you do not know the size (like std::vector .)

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