c++ 如何将文本从.txt文件读入数组?

mpbci0fu  于 2022-11-27  发布在  其他
关注(0)|答案(3)|浏览(154)

我想打开一个文本文件并完整地读取它,同时用c将其内容存储到变量和数组中。下面是我的示例文本文件。我想将第一行存储到一个整型变量中,第二行转换为3d数组索引,最后一行转换为字符串数组的5个元素。我知道如何打开文件进行阅读,但我还没有“我不知道如何阅读某些单词并将它们存储为整数或字符串类型。我不确定如何在c中完成这一点,任何帮助都非常感谢。

3
2 3 3
4567 2939 2992 2222 0000
eyh26e7m

eyh26e7m1#

阅读文本文件中的所有int:

#include <fstream>

int main() {
    std::ifstream in;
    in.open("input_file.txt")
    // Fixed size array used to store the elements in the text file.
    // Change array type according to the type of the elements you want to read from the file
    int v[5];
    int element;

    if (in.is_open()) {
        int i = 0;
        while (in >> element) {
            v[i++] = element;
        }
    }

    in.close();

    return 0;
}
tcomlyy6

tcomlyy62#

包括fstream

#include <fstream>

并使用ifstream

std::ifstream input( "filename.txt" );

要能够逐行阅读:

for( std::string line; std::getline( input, line ); )
{
    //do what you want for each line input here
}
vptzau2j

vptzau2j3#

试试这个:

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::ifstream file("filename.txt"); // enter the name of your file here

    int firstLine;

    int secondLine;
    const int X = 3;
    const int Y = 1;
    const int Z = 1;
    int ***arr3D;

    std::string myArray[5];
    std::string myString;

    if (file.is_open())
    {
        // store the first line into an integer variable
        file >> firstLine;

        // store the second line into a 3d array index
        arr3D = new int**[X];
        for (int i = 0; i < X; i++)
        {
            arr3D[i] = new int*[Y];

            for (int j = 0; j < Y; j++)
            {
                arr3D[i][j] = new int[Z];

                for (int k = 0; k < Z; k++)
                {
                    file >> secondLine;
                    arr3D[i][j][k] = secondLine;
                }
            }
        }

        // store the final line into 5 elements of a string array
        int i = 0;
        while (file >> myString)
        {
            myArray[i] = myString;
            i++;
        }
    }

    file.close();

    std::cout << firstLine << std::endl;

    for (int i = 0; i < X; i++)
    {
        for (int j = 0; j < Y; j++)
        {
            for (int k = 0; k < Z; k++)
            {
                std::cout << arr3D[i][j][k] << std::endl;
            }
        }
    }

    for (int i = 0; i < 5; i++)
    {
        std::cout << myArray[i] << std::endl;
    }

    return 0;
}

相关问题