sprintf in C and C++

This is a discussion on sprintf in C and C++ within the C++ Programming forums, part of the General Programming Boards category; Hi all, I need to print characters and integers together in a string. I know about sprintf in C as ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    1

    sprintf in C and C++

    Hi all,
    I need to print characters and integers together in a string.

    I know about sprintf in C as it is used like the following:

    char str[] = "num%d num%d num%d";

    int a = 5;
    int b = 6;
    int c = 7;

    sprintf(str,a,b,c) ;


    Is there a same function which does the same in C++.

    I tried sprintf as following:

    char str[] = "num%d";
    int a = 5;
    sprintf(str,a);

    This makes "a" a character and puts it in "str" but does not do the same as sprintf in C.

    I tried searching for a C++ library function but was not able to find one. any help is appreciated.Thanks in advance.

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    Both of your examples are broken, in C and C++. sprintf takes a buffer as it's first argument, and a format string as it's second. The C++ version differs only in that it's header is named <cstdio> rather than <stdio.h> and, like all C++ functions it lives in the std namespace, so to use the library function you would use std::sprintf(buff,"Num:%d",a); and are now free to name your own function sprintf. What kind of sick pervert wants to name thier own function sprintf I do not want to know, but we're all about options here in C++ land. The prefered C++ way to do these things is to use stringstreams. These are built around std::string's so they can expand as space is needed, rather than just writing over whatever is convenent in the surprising and interesting way sprintf and has made famous. They also work on anything with <<, >> operators, including those you define yourself.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Using stringstreams is like doing file input/output except instead of a file, you use a variable to write to and read from. Here is an example:
    Code:
    #include <iostream>
    #include <sstream>
    #include <string>
    using namespace std;
    
    
    int main ()
    {
    	int a = 10;
    	int b = 50;
    	char text[] = "some text";
    	
    	stringstream ss;
    	ss<<a<<text<<b;
    
    	cout<<ss.str()<<endl;  //turns what's in ss into a string type
    	
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21