首页 > 解决方案 > need help reading file contents into an array C++

问题描述

I want to be able to do $> ./program file.txt 8 and then read the 8 values inside file.txt into an array

heres the code I have right now but it doesn't work

int main(int argc, char *argv[])
{
    ifstream file;
    int size;
    int arr[size],val;
    for(int i=0;i<size;i++)
    {
        cin>>val;
        arr[i] = val ;
    }

标签: c++arraysfstream

解决方案


据我了解,您想从文本文件中读取一些值。你可以这样做:

int main()
{
    std::string textArray[8]; // array to store the data

    std::fstream textFile; // creating a file object

    textFile.open("text_file.txt", std::ios_base::in); // creating and opening a text file

    if (textFile.is_open()) // check to see if file opened sucessfully
    {
        for (int a = 0; a < 8; ++a)
        {
            getline(textFile, textArray[a]); // using getline to get the values of the file
            std::cout << textArray[a] << "\n";
        }

        textFile.close(); // closing the files after we're done using it
    }
}

如您所见,我们打开了一个文件,并用于getline()读取该文件的内容并将其存储在一个数组中。


推荐阅读