Asked  7 Months ago    Answers:  5   Viewed   73 times

I have to format std::string with sprintf and send it into file stream. How can I do this?

 Answers

67

You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string:

  char buff[100];
  snprintf(buff, sizeof(buff), "%s", "Hello");
  std::string buffAsStdStr = buff;

But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this:

  std::ostringstream stringStream;
  stringStream << "Hello";
  std::string copyOfStr = stringStream.str();
Tuesday, June 1, 2021
 
Markol
answered 7 Months ago
50

It means not found.

It is usually defined like so:

static const size_t npos = -1;

It is better to compare to npos instead of -1 because the code is more legible.

Saturday, June 12, 2021
 
koenHuybrechts
answered 6 Months ago
31
// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );

See format and its syntax

Tuesday, June 15, 2021
 
Blacksonic
answered 6 Months ago
68

The '%s' modifier of printf takes a char*, not a std::string.

You can write:

sprintf(command,"echo "something with a string %s" ", stringz.c_str());

Which gives you a const char* to the contents of a std::string. This shows one of the major weaknesses of sprintf -- no type checking!

Monday, August 30, 2021
 
MaxU
answered 4 Months ago
87

You can do it with the Boost.Format library, because you can feed the arguments one by one.

This actually enables you to achieve your goal, quite unlike the printf family where you have to pass all the arguments at once (i.e you'll need to manually access each item in the container).

Example:

#include <boost/format.hpp>
#include <string>
#include <vector>
#include <iostream>
std::string format_range(const std::string& format_string, const std::vector<std::string>& args)
{
    boost::format f(format_string);
    for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) {
        f % *it;
    }
    return f.str();
}

int main()
{
    std::string helloString = "Hello %s and %s";
    std::vector<std::string> args;
    args.push_back("Alice");
    args.push_back("Bob");
    std::cout << format_range(helloString, args) << 'n';
}

You can work from here, make it templated etc.

Note that it throws exceptions (consult documentation) if the vector doesn't contain the exact amount of arguments. You'll need to decide how to handle those.

Saturday, September 18, 2021
 
McAuley
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share