c++ 如何用 ifstream 读取txt文件的全部内容

比如txt文件名为a,该如何实现

#include <fstream>
ifstream fin("a.txt");
以后在程序中用 fin>> 流入变量。
当然a.txt要和exe在同一文件夹。
否则双引号中要加上路径,如c:\a.txt

若不懂,请参考c++文件流。追问

请问用什么方法可以将读取的内容保存至一个变量中呢

追答

如这样。
#include
#include
using namespace std;

ifstream fin("a.txt");

main()
{
int a;
fin>>a;
}
若a.txt 内容为
1
那么a在执行后会为1

追问

那如果txt内容为很多文字呢,该怎么实现呢

追答

依次来,
比方说
//////////a,txt////////////////
123 111 3333 a derf
321
/////////////////////////////////
//////////主程序////////////
main()
{
int a,b,c,d;
char ch;
string str;
fin>>a>>b>>c>>ch>>str>>d;
return 0;
}
运行完后,
a=123
b=111
c=3333
ch='a'
str="derf"
d=321

若你对c++标准流操作(cin, cout)熟悉的话,应该是不会有这个问题的,所以看你应该是新手。

你可以去买一本
c++ primer, 可帮你快速入门

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-07-31
using namespace std;
ifstream infile("a.txt");
if (!infile.bad())
{
// Dump the contents of the file to cout.
cout << infile.rdbuf();
infile.close();
}
第2个回答  2012-07-31
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifFile( "c:\\a.txt");
if( !ifFile )
{
return -1;
}
ifFile.seekg(0, ios::end);
int iFileSize = ifFile.tellg();
ifFile.seekg( 0, ios::beg );
char *pBuffer = new char[iFileSize];
if ( pBuffer == NULL )
{
return -1;
}
memset( pBuffer, 0, iFileSize );
ifFile.read( pBuffer, iFileSize );
return 0;
}本回答被网友采纳
第3个回答  2012-07-31
把文件名的后缀更改为: a.txt 就可以了。
第4个回答  2012-07-31
ifstream in("c:\\a.txt");
in.read( ... );
相似回答