现在的位置: 首页 > 综合 > 正文

【面试】文件操作

2013年02月23日 ⁄ 综合 ⁄ 共 976字 ⁄ 字号 评论关闭

题目要求:
(1)从文本1.txt读取内容,输出到文件2.txt中
(2)1.txt的文件内容例如:
123456
我爱中国abc
abcdef
输出为2.txt
a我1
b爱2
c中3
d国4
ea5
fb6
 c

思路:我只实现了对英文字符的

#include <iostream>
#include <fstream>
#include <string>

using  namespace std;

int getTextLine(const char *path, int &line_num, int &max_txt)
{
	if (NULL == path)
	{
		return -1;
	}


	ifstream ifile(path);
	if (!ifile)
	{
		return -1;
	}

	string str;
	int count = 0;
	int max_txt_num = 0;


	while (getline(ifile, str))
	{
		max_txt_num = str.length();
		max_txt = max_txt > max_txt_num ? max_txt: max_txt_num;
		
		line_num++;
		count++;
	}

	return count;
}



int main(int argc, char* argv[])
{
	
    int nLine = 0; /*文件的行数*/
	int max_txt = 0;

	ifstream iFile("c:\\1.txt"); 
	if(!iFile)
	{
		cout << "打开文件失败"<<endl;
	}

	/*获取该文件有多少行*/
	getTextLine("C:\\1.txt", nLine, max_txt);

	string *str = new string[nLine];
	
	
	ofstream oFile("c:\\2.txt");
	if (!oFile)
	{
		cout << "2.txt文件不存在";
	}

	for (int i = 0; i < nLine; i++)
	{
		getline(iFile, str[i]);
		cout << str[i] << endl;
	}

	for (int k = 0; k < max_txt; k++)
	{
		for (int j = nLine-1; j >= 0; j--)
		{
			if(k > str[j].length())
			{
				cout << " ";
				oFile << " ";
				
			}
			else
			{
				cout << str[j][k];
				oFile << str[j][k];
			}
		}

		oFile <<endl;
		cout << endl;
	}

	delete []str;
	return 0;
}

抱歉!评论已关闭.