要读取的文件:

逐个字符读取:
方式一:>>读取
#include<iostream>
#include<fstream>
using namespace std;
int main() {
char c[30];
int i = 0;
ifstream infile("A.txt");
if (!infile) {
cout << "open A.txt error!";
exit(1);
}
//infile >> noskipws; //强制读入每一个字符,包括空格、转折
while (infile >> c[i]) {
cout << c[i];
i++;
}
cout << endl;
c[i] = '\0'; //注意,保证strlen(c)的值正确
cout << "length:" << strlen(c) << endl;
cout << c << endl;
infile.close();
return 0;
}
方式二:判断EOF符号
#include<iostream>
#include<fstream>
using namespace std;
int main() {
char c[30];
int i = 0;
ifstream infile("A.txt");
if (!infile) {
cout << "open A.txt error!";
exit(1);
}
//infile >> noskipws; //强制读入每一个字符,包括空格、转折
while (!infile.eof()) {
infile >> c[i];
cout << c[i];
i++;
}
cout << endl;
c[--i] = '\0'; //注意,此时 i 必须先减1,才能保证strlen(c)的值正确
cout << "length:" << strlen(c) << endl;
cout << c << endl;
infile.close();
return 0;
}
以上均可以替换成
#include<vector>
vector<类型> c;
同一类型 x;
while(infile>>x){
c.push_back(x);
}
for(int i=0;i<c.size();i++){
cout<<c[i]<<" ";
}
逐行读取:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
ifstream infile("A.txt");
if (!infile) {
cout << "open A.txt error!";
exit(1);
}
//方式一:
string str;
while (getline(infile, str)) { //只能传入string类型的参数
cout << "length:" << str.length() << " ";
cout << str << endl;
}
/*
//方式二:
string str;
while (infile>>str) {
cout << "length:" << str.length() << " ";
cout << str << endl;
}
*/
/*
//方式三:
string str;
while (!infile.eof()) {
infile >> str;
cout << "length:" << str.length() << " ";
cout << str << endl;
}
*/
infile.close();
return 0;
}
本文详细介绍使用C++进行文件读取的多种方法,包括逐个字符读取、逐行读取以及使用向量存储数据的技巧。通过具体代码示例,展示了如何打开文件、读取内容并正确关闭文件,适合初学者和需要复习文件操作的开发者。
11万+

被折叠的 条评论
为什么被折叠?



