【问题标题】:C++ Input Filestream cannot read a string from a fileC++ 输入文件流无法从文件中读取字符串
【发布时间】:2019-09-16 16:21:37
【问题描述】:

我正在尝试将文件“hello.txt”中的字符串读入 std::string。读取后字符串仍为空。

#include <fstream>
#include <string>
int main()
{
    std::fstream in("hello.txt");
    std::string a;
    in >> a;
}

【问题讨论】:

  • 你怎么可能知道a 是空的,如果你的程序在设置它之后立即退出,然后再使用它?
  • @JosephSible OP 可能在调试器中查看它,但你说得对,这是不完整的——例如,我们不知道 hello.txt 是否包含任何内容,或者它是否存在于该位置程序所期望的。最有可能设置了failbit
  • 我希望您将 hello.txt 放在错误的文件夹中或名称不正确。一些 IDE,如 Visual Studio,默认位置是项目文件所在的位置。您需要将文件放在可执行文件所在的其他 IDE。同样在 Windows(默认情况下隐藏已知扩展名)上,您可能会对扩展名隐藏感到困惑,您的文件实际上可能被命名为 hello.txt.txt

标签: c++ file io visual-studio-2017


【解决方案1】:

您的代码是正确的。可能是文件放错了地方,所以打不开。

试试这个代码:

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

int main()
{
    std::fstream in("output.txt");
    std::string a;
    if (in.is_open())
    {
        in >> a;
        std::cout << a << std::endl;
        in.close();
    }
    else
    {
        std::cout << "could not open file!" << std::endl;
    }
}

【讨论】:

  • 使用 try + catch 和 what() 处理异常,还可以打印更有用的错误消息。
猜你喜欢
  • 2019-04-10
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
相关资源
最近更新 更多