fstream以txt格式显示所有文本
fstream to display all text in txt
我想显示填充到输出中的所有文本,我使用下面的代码,我得到的代码和结果帖子只是有点超出
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
上面的代码只是简单地显示单词"This"并没有全部输出。我想要的是文件中的所有文本都显示在控制台中。。
char*
的重载operator>>
将只读取到第一个空白字符(这也是非常的风险,如果它试图读取比buf长度更长的单词,则最终会导致未定义的行为)。
只要编译器支持右值流重载(如果不支持,则必须创建一个本地ostream
变量,然后使用流运算符),以下操作应该以最简单的方式完成您想要的操作:
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << 'n';
}
尝试类似的东西
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << 'n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
希望对有所帮助
这不是读取文件的最佳方式。您可能需要使用getline并逐行读取。请注意,您使用的是固定大小的缓冲区,可能会导致溢出。不要那样做。
这是一个类似于你想要实现的目标的例子,而不是最好的做事方式。
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
这是一个重复的问题:
将ifstream中的一行读取到字符串变量中
正如您从C++的文本输入/输出中所知,cin
最多只能读取一个换行符或一个空格。如果要读取整行,请使用std::getline(b_file, str)
相关文章:
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- 尝试使用 WinBGI 显示文本时出现编译器错误
- 动态填充的组合框不显示文本,列表未定义
- 使用 fltk 时,文本未显示在已编译的窗口中
- PyQT - 在 QTableWidget 单元格中显示垂直文本
- 如何使用IExecuteCommand和动词在上下文菜单外壳扩展中显示本地化文本和自定义图标?
- 如何在 qt c++ 中更新 QWindow,文本不显示
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- sf::文本不显示?
- 在QT C++编辑Qtable模型数据时,我需要得到一个小盒子,我需要显示编辑文本,这怎么可能?
- QTreeWidgetItem 突出显示文本问题
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 如何通过单击按钮在QTextEdit中显示文本?
- 在C Windows程序中显示文本文件内容
- 如何在重新调整窗口大小时使文本显示在窗口中心,visualc++
- 打开 GL 文本显示时未处理的异常
- 如何要求输入后的文本显示下一行在c++中
- 如何将文件的路径(或任何文本)显示/附加到编辑框中?(C++ Win32 API)
- 将格式化文本显示到 QTextEdit 就像在 C 的 printf 中一样