Thread: String incorrect for output command target

  1. #16
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    As you should have noticed when you read the manual on c_str(), but didn't, the result of c_str() is not modifiable, so any attempt to add something at the end is doomed to failure. Also, when C++ says const, it means it, so it laughs at your attempt to remove the const condition.

    Since c_str() is not modifiable, you have to add rpg to the string filenameo itself. And if you don't plan to keep the name around, then there's no good reason to not just put the call in the constructor (and it's what people will expect, too), like so:
    Code:
    std::ofstream output(filenameo.c_str());

  2. #17
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The first problem is due to filename being a char* instead of a const char*. The second problem is due to you attempting to concatenate "rpg" to filename, but such concatenation using operator+ only works (correctly) on std::string. As such, just write:
    Code:
    std::string filename;
    
    // ...
    
    cin >> filename;
    filename += "rpg";
    std::ofstream output(filename.c_str());
    Alternatively, you can write:
    Code:
    std::ofstream output((filename + "rpg").c_str());
    But it may be better to concatenate the "rpg" to the string if you should need to reuse the filename, e.g., to show the user what file was opened.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM