Tiancl 发表于 2022-2-26 23:13:24

c++读取txt文件

c++读取txt文件,txt文件大概是五个字符串一行,然后差不多一百行,怎么读取,并且存入一个string类的二维数组。

c_cpp_python 发表于 2022-2-26 23:25:39

你这个问的就有点笼统...
那我就给你贴一段书本上讲文件IO的代码吧...

// fileio.cpp -- saving to a file
#include <iostream> // not needed for many systems
#include <fstream>
#include <string>

int main()
{
    using namespace std;
    string filename;

    cout << "Enter name for new file: ";
    cin >> filename;

// create output stream object for new file and call it fout
    ofstream fout(filename.c_str());

    fout << "For your eyes only!\n";      // write to file
    cout << "Enter your secret number: ";   // write to screen
    float secret;
    cin >> secret;
    fout << "Your secret number is " << secret << endl;
    fout.close();         // close file

// create input stream object for new file and call it fin
    ifstream fin(filename.c_str());
    cout << "Here are the contents of " << filename << ":\n";
    char ch;
    while (fin.get(ch))   // read character from file and
      cout << ch;         // write it to screen
    cout << "Done\n";
    fin.close();
    // std::cin.get();
    // std::cin.get();
    return 0;
}
页: [1]
查看完整版本: c++读取txt文件