假设我在D盘有一个文本test.txt,里面有hello world,我把它输出。
#include <fstream.h>
#include <string.h>void main()
{
fstream file1;
        string a;
file1.open("D:test.txt",ios::out,0);
file1>>a;
        cout<<a<<endl;
file1.close();
}
但是不行,哪位大侠说一下。

解决方案 »

  1.   

    这个问题我自己解决了,是用错类了,应该用ifstream来写。
    #include <fstream.h>
    #include <string.h>void main()
    {
    ifstream in("D:test.txt");
    int a;
    in>>a;
    in.close();
    cout<<a<<endl;
    }
    D盘中test.txt的内容为1,确实输出了1。可以当我把文本内容设为hello world时,我这么写:
    #include <fstream.h>
    #include <string.h>void main()
    {
    ifstream in("D:test.txt");
    string a;
    in>>a;
    in.close();
    cout<<a<<endl;
    }
    此时编译报错:
    error C2065: 'string' : undeclared identifier
    求解。
      

  2.   

    #include <string>
    #include <fstream>using namespace std;
      

  3.   

    问题解决了,楼上的少添了一个头文件#include <iostream>,完整代码如下:
    #include <string> 
    #include <fstream> 
    #include <iostream>using namespace std;void main() 

    ifstream in("D:test.txt"); 
    string a; 
    in>>a; 
    in.close(); 
    cout<<a<<endl; 
    }
    但是又有问题出来了,只打印了hello,而world没打印出来,是不是默认in>>a;到第一个空格符前就停止,那我怎么连同空格符后的那个world呢一起打印出来呢?要打印出一大段文字,这是一个最基本问题。
    继续求教。
      

  4.   

    确实像你说的那样。因为对于>>,输入string的时候,遇到第一个空格或制表符等字符的时候,就会停止。其实,如果你想输出很多string的时候,可以用in>>a作为while的条件,这是个思路。你可以试试。今天太晚了,我没有试,如果你解决不了,我再写吧。