0

My function is:

void Matrix::WriteToFile(std::string fname) const
{
    ofstream myfile;
    myfile.open ("std::string fname.txt");
    for (int i = 0; i<data_.size(); i++)
    myfile << data_[i] << " ";
    myfile.close();
}

and then in the main I have A.WriteToFile("hello"), but it's saving it as fname still? Can anyone please tell me what I'm doing wrong?

Thanks in advance!

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by sexyzebra19
Featured Replies
  • 1

    This line:[icode]myfile.open ("std::string fname.txt");[/icode] is just plain silly. It'll open a file called "std::string fname.txt". Changing it to [icode]myfile.open (fname.c_str());[/icode] will probably have a more "expected" result :) A tip: It's a good idea to check if your file is really open before writing to it. [edit] and what is … Read More

  • 1

    Just in case you don't know about illegal filenames, see [URL="http://en.wikipedia.org/wiki/File_name#Reserved_characters_and_words"]Filename / Reserved characters and words[/URL] So having a filename containing e.g. semicolon(s), would quite likely be a mission impossible. Read More

1

This line: myfile.open ("std::string fname.txt"); is just plain silly. It'll open a file called "std::string fname.txt".
Changing it to myfile.open (fname.c_str()); will probably have a more "expected" result :)
A tip: It's a good idea to check if your file is really open before writing to it.

[edit]
and what is "data_"? Is it globally declared??

Edited by Nick Evan: n/a

0

and what is "data_"? Is it globally declared??

Thanks Nick, yes data_ is stored in a header under a private variable.

It's now saving the correct filename, however how do I specify it to a .txt file?

I tried myfile.open (fname.c_str().txt); but no luck!

0

Fixed it with

myfile.open ( (fname+".txt").c_str() );

thanks both of you :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.