将字符串设置为文件内容c++
Set string to file contents c++
我想知道是否有一种简单的方法可以将 std::string
设置为等于 C++ 中文件的内容。到目前为止,我的想法是这样的:(虽然我没有测试过,所以我不知道它是否有效)
#include <fstream>
#include <string>
int main(int argc, char *argv[]){
fstream in("file.txt");
string str;
str = in;
return 0;
}
这是实现这个的方法吗?如果没有,是否有一种简单的方法可以做到这一点?谢谢!
这是使用 vector<string>
的一种可能解决方案,每个元素都是一行。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// vector that will store all the file lines
vector<string> textLines;
// string holding one line
string line;
// attach input stream to file
ifstream inputFile("data.txt");
// test stream status
if(!inputFile)
{
std::cerr << "Can't open input file!\n";
}
// read the text line by line
while(getline(inputFile, line))
{
// store each line as vector element
textLines.push_back(line);
}
// optional (stream object destroyed at end of function scope)
inputFile.close();
return 0;
}
试试这个
#include <fstream>
#include <cstdlib>
std::string readText(const char* fileName)
{
std::ifstream file(fileName);
if (!file.good())
{
std::cout << "file fail to load..." << fileName;
exit(1);
}
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
有一个标准的方法:
std::ifstream file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string content( buffer.str() );
参考资料
我想知道是否有一种简单的方法可以将 std::string
设置为等于 C++ 中文件的内容。到目前为止,我的想法是这样的:(虽然我没有测试过,所以我不知道它是否有效)
#include <fstream>
#include <string>
int main(int argc, char *argv[]){
fstream in("file.txt");
string str;
str = in;
return 0;
}
这是实现这个的方法吗?如果没有,是否有一种简单的方法可以做到这一点?谢谢!
这是使用 vector<string>
的一种可能解决方案,每个元素都是一行。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// vector that will store all the file lines
vector<string> textLines;
// string holding one line
string line;
// attach input stream to file
ifstream inputFile("data.txt");
// test stream status
if(!inputFile)
{
std::cerr << "Can't open input file!\n";
}
// read the text line by line
while(getline(inputFile, line))
{
// store each line as vector element
textLines.push_back(line);
}
// optional (stream object destroyed at end of function scope)
inputFile.close();
return 0;
}
试试这个
#include <fstream>
#include <cstdlib>
std::string readText(const char* fileName)
{
std::ifstream file(fileName);
if (!file.good())
{
std::cout << "file fail to load..." << fileName;
exit(1);
}
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
有一个标准的方法:
std::ifstream file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string content( buffer.str() );
参考资料