c使用ifstream来读取txt文件,控制格式很方便



使用ifstream来读取txt文件,控制格式很方便.

#include<iostream>
#include<fstream>

using namespace std;

int main()
{
ifstream fin(“hello.txt”);
while (fin!=NULL)
{
int a;
char str[10];
fin>>a;
fin>>str;
cout<<a<<”+char”<<str<<endl;
}
}

使用ifstream来读取txt文件,控制格式很方便

使用ifstream来读取txt文件,控制格式很方便
附:
问:
ifstream指针如何回到开始?
答:
增加该语句:fin.seekg(ios::beg);

以下是更加方便的操作方法,转载自别人的博客:http://blog.csdn.net/wangwei200508/article/details/5655095
觉得答案正确以后,得提交代码,这时候不能把这个测试也提交上去。可以通过以下2种方式解决:
1、把文件开始的 //#define NDEBUG 的注释符去掉
2、把所有在 #ifndef NDEBUG 和 #endif 之间的代码段(包括那2句)都删掉
然后复制提交。
#include<iostream>
//#define NDEBUG

#ifndef NDEBUG
#include<fstream>
#endif


using namespace std;

int main()
{
#ifndef NDEBUG
// 打开必要的 files
ofstream outfile(“out.txt”,ofstream::app);
ifstream infile(“in.txt”,ifstream::in);
// 将要从屏幕读取或输出到屏幕上的信息转移到 files上
#define cin infile
#define cout outfile
// 输出调试时间,方便对比
cout<<”Compiled on “<<__DATE__
<<” at “<<__TIME__<<endl
<<”—– start —–”<<endl;
#endif

//以下是解题的过程
int i_temp = 0,
i_temp2 = 0;
while(cin>>i_temp)
{
if(i_temp%2)
{
i_temp2 = (i_temp+1)>>1;
cout<<i_temp2*i_temp<<endl<<endl;
}
else
{
i_temp2 = i_temp>>1;
cout<<i_temp2*(i_temp+1)<<endl<<endl;
}
}

//这里收个尾,对outfile末尾进行标记,关闭files
#ifndef NDEBUG
cout<<”—– end —–”<<endl<<endl;
outfile.close();
infile.close();
#endif

return 0;
}

http://blog.sina.com.cn/s/blog_75e063c101014a60.html