【问题标题】:C++: Read from files? [duplicate]C++:从文件中读取? [复制]
【发布时间】:2010-09-21 22:36:58
【问题描述】:

可能重复:
Reading through file using ifstream

我正在尝试找到一种方法来从文件中读取某些内容,将其放入字符串中,然后将其输出到屏幕上。如果你知道怎么做,你能举个例子吗?

【问题讨论】:

标签: c++ file load


【解决方案1】:
ifstream infile("myfile.txt");
std::string line;

// Reads the first line from the file and stores it into 'line'
std::getline(infile, line);

infile.close();
std::cout << line;

此代码将读取文件的整个第一行。 如果你想逐行读取文件,你可以这样做:

while (!infile.eof) {
  std::getline(infile, line);
  std::cout << line << "\n"; // Not sure if std::getline includes the line terminator
}

不确定“需要阅读一些东西”是什么意思,但您可以使用字符串流进行转换。

【讨论】:

    【解决方案2】:
    ifstream fin ("input.txt");
    
    char line [200];
    streamsize size (200);
    fin.getline(line, size);
    //or you could do:
    //  string str; fin >> str;
    //for every space sepped string in the file
    cout << line << endl;
    

    【讨论】:

    • 使用std::string更安全。
    猜你喜欢
    • 2011-04-27
    • 2011-03-06
    • 2018-01-07
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2021-09-07
    相关资源
    最近更新 更多