【问题标题】:ifstream reading in blanks when there is data in file当文件中有数据时,ifstream 读取空白
【发布时间】:2013-07-31 23:14:48
【问题描述】:

我正在尝试使用 c++ ifstream 从文本文件中读取数据,但由于某种原因,下面的代码不起作用。该文件包含两个用空格分隔的数字。但是,此代码不会打印任何内容。谁能给我解释一下出了什么问题?

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void readIntoAdjMat(string fname) {
    ifstream in(fname.c_str());
    string race, length;
    in >> race >> length;
    cout << race << ' ' << length << endl;  
    in.close();
}

int main(int argc, char *argv[]) {
    readIntoAdjMat("maze1.txt");
}

【问题讨论】:

  • 如果您正确打开了文件并成功阅读了您的条目,您应该这样做。从问题描述我猜它无法打开文件。
  • 您实际上并没有检查文件是否正确打开。它可能从未打开过吗?

标签: c++


【解决方案1】:

您应该始终在成功的情况下测试与外部实体的交互:

std::ifstream in(fname.c_str());
std::string race, length;
if (!in) {
    throw std::runtime_error("failed to open '" + fname + "' for reading");
}
if (in >> race >> length) {
    std::cout << race << ' ' << length << '\n';
}
else {
    std::cerr << "WARNING: failed to read file content\n";
}

【讨论】:

  • 我认为无法读取文件是一个错误。不是你应该警告的事情。
  • 使用它时会打印出“警告:读取文件内容失败\n”。为什么读取文件内容失败?
  • @user2640052:如果文件中至少有两个由空格分隔的字符串,则它不应该失败。您可能需要阅读并测试各个字段以查看导致失败的字段。
  • @Cole"Cole9"Johnson:我认为这取决于。如果读取文件对程序的运行至关重要,那很可能是一个错误。如果文件包含要应用的很好的自定义设置,那么如果内容格式不正确也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多