读取文本 添加行数并输出
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<stdlib.h>
using namespace std;
vector<string>saveText; //vector 数组存储从文本读取的行数据
void readFile(string fileName) {
ifstream infile;
infile.open(fileName.data());
string tempStr; //临时存储用字符串
int lineCnt=1; //行统计
while(getline(infile,tempStr)) {
cout<<"第"<<lineCnt<<"行:"<<tempStr<<endl; //输出读取文本行
char lineCntChar[50];
itoa(lineCnt,lineCntChar,50);
string str = lineCntChar;
string tempSave =str+" "+tempStr; //增加行标记
saveText.push_back(tempSave); //加入存储数组
lineCnt++;
}
infile.close(); //关闭文件流
}
void writeFile(string fileName){
ofstream ofile;
ofile.open(fileName.data());
for(int i=0;i<saveText.size();i++){
ofile<<saveText[i]<<endl;
}
ofile.close();
}
int main() {
cout<<"READ FILE"<<endl;
string readFileName = "fileRead.txt";
readFile(readFileName);
cout<<"[Complete]READ FILE"<<endl;
cout<<"WRITE FILE"<<endl;
string writeFileName = "fileWrite.txt";
writeFile(writeFileName);
cout<<"[Complete]WRITE FILE"<<endl;
return 0;
}
1、逐行读入
void readTxtLine(string fileName)
{
ifstream infile;
infile.open(fileName.data()); //关联文件流对象与文件
string s;
while (getline(infile, s)) //逐行读取
{
cout << s << endl;
}
infile.close();
}
2、字符输入 忽略空格回车
void readTxtChar(string fileName)
{
ifstream infile;
infile.open(fileName.data());
char c;
while (!infile.eof())
{
infile >> c;
cout << c <<" ";
}
cout<<endl;
infile.close();
}
字符读入 包含空格回车
void readTextCharNoskipws(string fileName){
ifstream infile;
infile.open(fileName.data());
char c;
infile >> noskipws;
//no skip white space 不忽略任何地方的空格
while(!infile.eof()){
infile>>c;
cout<<c;
}
cout<<endl;
infile.close();
}