2

I ran into such a problem: i wrote some code and when i try to format some data (especially strings) i got strange result

#include <iostream>     // std::cout, std::endl
#include <string.h>
#include <vector>
#include <cstdarg>
#include <sstream>

using namespace std;

void va_cout(string format, ...)
{
    vector<char> buf(256);
    va_list args;
    va_start(args, format);
    vsnprintf_s(&buf[0], buf.size(), buf.size() + strlen(format.c_str()), format.c_str(), args);
    va_end(args);
    cout << endl << "apply va_cout(""%s"", s) = " << &buf[0] << endl;
}

int main() {
    string s("myString");
    cout << endl << s << endl;
    va_cout("%s", s);
    va_cout("%s", s.c_str());
    return 0;
}

// results

  1. myString

  2. apply va_cout(%s, s) = └¤#

  3. apply va_cout(%s, s) = myString

why it returns line 2 ?

1 Answer 1

4

%s can be used only with char * and const char *. You are passing a std::string and treating it like a char * in vsnprintf_s(). There is no implicit conversion from std::string to char *. You need to call std::string::c_str() for that.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you. i'm trying to understand how to round out std::string::c_str() using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.