C++输入文件流无法从文件中读取字符串

C++ Input Filestream cannot read a string from a file

本文关键字:文件 读取 字符串 输入 C++      更新时间:2023-10-16

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

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

你的代码是正确的。也许文件位于错误的位置,因此无法打开。

试试这个代码:

#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;
}
}