some Problems/Questions with std::string and printf

Started by
4 comments, last by Radagar 21 years, 7 months ago
Hello all, I tried searching for this on Google, but didn''t get any good results, and I can''t search the forums right now, that option is disabled.. Does printf() not work with std::string ''s? Take this snippit of code for example...
  
#include <string>

#include <iostream>

using namespace std;

int main()
{
     string a;
     string b;
     cout<<"Enter a word"<<endl;
     cin>>a;
     cout<<"\n\n Enter another word"<<endl;
     cin>>b;
     printf("the 2 words were %s and %s",a,b);
     return 0;
}
  
Upon compilation, you get

"The two words were  and "
 
Am I just using the wrong syntax for printf? I normally have only used cin and cout up to this point. Any help is appreciated! ~~~~~~~~~~~ Chris Vogel ~~~~~~~~~~~
WyrmSlayer RPG - In Early Development
Advertisement
printf is a C function and hence doesn''t know about std::string.

Use .c_str() to get a char* from a string.





"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
Radagar:

Why are you even using printf() at all? You can get the same functionality as this:

printf("the 2 words were %s and %s",a,b);

by doing this:

cout << "the 2 words were " << a << " and " << b << endl;

John.
quote:Original post by JohnAD
Radagar:

Why are you even using printf() at all? You can get the same functionality as this:

printf("the 2 words were %s and %s",a,b);

by doing this:

cout << "the 2 words were " << a << " and " << b << endl;

John.


That's true, but I like the format for printf() - but now that I know it doesn't work right with new std::strings, I probably will just stick to cout.

Thanks to you both!



~~~~~~~~~~~
Chris Vogel
~~~~~~~~~~~
edit = typo

[edited by - Radagar on September 10, 2002 12:18:01 PM]
WyrmSlayer RPG - In Early Development
It does work with strings...

printf( buf, "%s", a.c_str( ) ) ;

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
quote:Original post by Paradigm Shifter
It does work with strings...

printf( buf, "%s", a.c_str( ) ) ;

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley


Aye, I understood that, just meant that it doesn''t work without adding the extra procedure to return the char* inside the string (I think that''s how it works).

Anyway, thanks.

WyrmSlayer RPG - In Early Development

This topic is closed to new replies.

Advertisement