我想std::string用c ++ 读取文本文件的全部内容到一个对象.
使用Python,我可以写:
text = open("text.txt", "rt").read()
Run Code Online (Sandbox Code Playgroud)
它非常简单而优雅.我讨厌丑陋的东西,所以我想知道 - 用C++读取文本文件最优雅的方法是什么?谢谢.
我正在构建一个以这种格式获取输入文件的程序:
title author
title author
etc
and outputs to screen
title (author)
title (author)
etc
Run Code Online (Sandbox Code Playgroud)
我目前遇到的问题是错误:
"ifstream infile的类型不完整,无法定义"
以下是该计划:
#include <iostream>
#include <string>
#include <ifstream>
using namespace std;
string bookTitle [14];
string bookAuthor [14];
int loadData (string pathname);
void showall (int counter);
int main ()
{
int counter;
string pathname;
cout<<"Input the name of the file to be accessed: ";
cin>>pathname;
loadData (pathname);
showall (counter);
}
int loadData (string pathname) // Loads data from infile into arrays
{
ifstream infile; …Run Code Online (Sandbox Code Playgroud)