0

I am trying to create a Windows Forms Application in Visual C++ 2010. I have saved some particular string in string variable "stat" like:

System::String ^stat = "sample string";

The problem is, I cannot write it to a text file using ofstream. When I try this:

if ( opstat == true ) // opstat is a bool variable
{
    ofstream outf("mytxt.txt",ios::app);
    outf << stat;
    outf.close();
}

Compiler returns an error:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'System::String ^' (or there is no acceptable conversion)

And a huge error that goes on forever like:

1>          D:\Development\Visual Studio 2010\VC\include\ostream(447): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(long double)'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]

What am I supposed to do here?

P.S. I have already included all necessary headers (or the ones I think are necessary) like string, fstream, istream, iomanip etc.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Uzair A.
  • 1,586
  • 2
  • 14
  • 30
  • Hmm, I assume you are using std::ostream? So what exactly is System::String? The problem seems to be that there is no "<<" operator defined in std::ostream with your "System::String" as second operand, whereas with "std::String" it would work. – user905686 Dec 19 '11 at 18:49
  • 2
    Are you aware of the difference between [c++](http://en.wikipedia.org/wiki/C%2B%2B) and [c++/cli](http://en.wikipedia.org/wiki/C%2B%2B_CLI)? I ask because you tagged with the former, but this code is the latter. – Benjamin Lindley Dec 19 '11 at 18:50
  • @user905686: `System::String` refers to the .NET String class I think. – dreamlax Dec 19 '11 at 18:59

2 Answers2

2

std::ofstream is an C++ Standard Library function, and it's not built to support System::String^. If you want to write to a file from a System::String^, you should use the System::IO::FileStream class. Otherwise, use a std::string instead of System::String^.

jzila
  • 724
  • 4
  • 11
  • `ofstream` is not, and never was part of the STL. The term is "The C++ Standard Library", and that also covers the parts that actually did originally come from the STL. – Benjamin Lindley Dec 19 '11 at 19:06
2

I think you have to convert System::String ^stat to std::string. See below link how to convert:

C++/CLI Converting from System::String^ to std::string

Community
  • 1
  • 1
Sanish
  • 1,699
  • 1
  • 12
  • 21
  • 1
    After learning how to convert `System::String` to `std::string`, perhaps as an exercise, implement a stream inserter that allows for type `System::String^`. – dreamlax Dec 19 '11 at 19:24