背景:武汉某211考研复试机试要求文件读写,自己准备了一下,结果机试取消了,也许是今年时间比较紧迫?我个人觉得以后会恢复机试,并且自己在社区里也没有找到很符合要求的c++代码,因此分享自己的代码以供参考,希望可以帮助后来人
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char buff[256];
ifstream inFile;
ofstream outFile;
inFile.open("C:\\Users\\administrator 2\\Desktop\\test.txt", ios::in);
outFile.open("C:\\Users\\administrator 2\\Desktop\\output.txt", ios::out);
if (inFile&& outFile) //条件成立,则说明文件打开成功
{
while (!inFile.eof())//eof函数当到达文件末尾时返回true
{
inFile.getline(buff,100);//这里getline一次循环读取一行,第二次getline把buff中第一次读取的覆盖掉了,因此在循环结束后buff为空.100应该是字符流最大长度
cout << buff << endl;
outFile << buff << endl;//向outFile中写入内容
}
}
else
cout << "file doesn't exist" << endl;
inFile.close();//读写操作完成后要关闭文件
outFile.close();
}
以上是最简单的文件读写,在真题里一般还会要求将数字读入数组以便操作,需要用到以下代码,关键在于strtok_s()函数的使用
#define ROW 3 // 定义输入文件中有几行数据
#define COLUMN 4 // 定义输入文件中有几列数据
// 将输入文件中用空格隔开的数字读入一个二维数组中
void readInToMatrix(fstream& in, string FilePath, int data[ROW][COLUMN]) {
in.open(FilePath, ios::in);//打开一个file
if (!in.is_open()) {
cout << "Can not find " << FilePath << endl;
system("pause");
}
string buff;
int i = 0;//行数i
while (getline(in, buff)) {
vector<double> nums;
char* s_input = (char*)buff.c_str();
const char* split = " ";
char* ptr = NULL;
char* p = strtok_s(s_input, split, &ptr); // 以空格为分隔符拆分字符串
double a;
while (p != NULL) {
a = atof(p);
nums.push_back(a);
p = strtok_s(NULL, split, &ptr);
}
for (int b = 0; b < nums.size(); b++) {
data[i][b] = nums[b];
}
i++;
}
in.close();
}
待解决的问题:中文字符的读入。一个汉字需要3个(也可能是2个?)char型变量来存储 ,因此不能像处理数字一样处理汉字。21年机试就有一个处理中文字符串的题,不知道可不可以用宽字符wchar来解决,反正我没做出来