需要帮助将文件内容读入数组C ++

问题描述 投票:0回答:1

我希望能够执行$> ./program file.txt 8然后将file.txt中的8个值读入数组中

这里是我现在拥有的代码,但是它不起作用

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++ arrays fstream
1个回答
0
投票

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

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()读取了文件的内容并将其存储在数组中。

© www.soinside.com 2019 - 2024. All rights reserved.