C++ 从C+;格式的文本文件获取内容+;
我有以下功能,以以下方式将特定格式的内容保存在文本文件中:C++ 从C+;格式的文本文件获取内容+;,c++,file,C++,File,我有以下功能,以以下方式将特定格式的内容保存在文本文件中: #include <fstream> #include <iostream> #include <iomanip> int main () { using namespace std; fstream fs; string str1 = string("1"); string str2 = string("12"); string str3 = s
#include <fstream>
#include <iostream>
#include <iomanip>
int main ()
{
using namespace std;
fstream fs;
string str1 = string("1");
string str2 = string("12");
string str3 = string("123");
string str4 = string("1234");
fs.open ("text.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << left << setfill(' ')
<< setw(10) << str1 << " | "
<< setw(10) << str2 << " | "
<< setw(10) << str3 << " | "
<< setw(10) << str4 << '\n';
fs.close();
return 0;
}
此函数用于读取文件的内容:
POS = 0123456789012345678901234567890123456789
TXT = 1 | 12 | 123 | 1234 |
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
}
cout<<output;
}
myReadFile.close();
return 0;
}
如何获取文件中的文本格式?对于
while(file)
循环,仅在循环中执行一次读取是唯一可接受的用例。但是,while(!file.eof())
在后面跟一个格式化的提取器操作符,或者在读取操作之后有任何处理时都是错误的。因此,请坚持使用一个好的旧无限循环,并在每次读取操作后进行测试
如果希望保留输入行的空格,例如处理固定大小的字段文件,IMHO最简单的方法是使用std::getline
作为一个整体读取该行:
#include <string>
...
string output;
if (myReadFile.is_open()) {
for(;;) {
getline(myReadFile, output);
if (!myReadFile) break
cout << output << "\n";
}
myReadFile.close();
}
首先请阅读。然后记住,重载的
>
操作符跳过空白。也许你会有兴趣读一读操纵器。最后,不要使用char
数组进行输入,使用std::string
。为什么不使用while(getline(…)
?我的意思不是(;)和break
的。@Someprogrammerdude:我只是想显示一个通用的读取循环。但是你是对的,只有一个getline
是例外。编辑。
#include <string>
...
string output;
if (myReadFile.is_open()) {
for(;;) {
getline(myReadFile, output);
if (!myReadFile) break
cout << output << "\n";
}
myReadFile.close();
}
while (getline(myReadFile, output)) {
cout << output << "\n";
}