473,406 Members | 2,956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

printf and string s

Hello all,

I'm trying to print a string on my screen... But the string comes from a
variable string... This is the code

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
string t = "tes";
printf ("%s", t );
system("PAUSE");
return EXIT_SUCCESS;
}
But this isn;t working.... the program is crashing when doing printf...
anyone know how to fix this ?
Sep 14 '06 #1
18 3717
"Joah Senegal" <bl****@hva.nlwrites:
>Hello all,
>I'm trying to print a string on my screen... But the string comes from a
variable string... This is the code
>#include <cstdlib>
#include <iostream>
#include <string>
>using namespace std;
>int main(int argc, char *argv[])
{
string t = "tes";
printf ("%s", t );
system("PAUSE");
return EXIT_SUCCESS;
}
>But this isn;t working.... the program is crashing when doing printf...
anyone know how to fix this ?
printf's expecting a C-style char-array "string". Give it what it wants
by using
printf ("%s", t.c_string());
or (better) use C++'s
cout << t;

Sep 14 '06 #2
Joah Senegal said the following on 14/09/2006 14:44:
Hello all,

I'm trying to print a string on my screen... But the string comes from a
variable string... This is the code

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
string t = "tes";
printf ("%s", t );
system("PAUSE");
return EXIT_SUCCESS;
}
You try tu use std::string with printf.

printf is a function of library C

now, you can do it with t.c_str(), but it's not very c++ compliant.

try this code:

#include <iostream>
#include <string>

int main( int argc, char *argv[] ) {
std::string t = "tes";
std::cout << t;
return EXIT_SUCCESS;
}
Sep 14 '06 #3
Joah Senegal wrote:
>
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
string t = "tes";
printf ("%s", t );
cout << t << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
If you *must* use printf, then pass t.c_str(), and you must include
<cstdio>. A std::string does not automagically convert to a char*. Why
did you include <iostreamif you weren't going to use it?

Sep 14 '06 #4
Stephane Wirtel wrote:
You try tu use std::string with printf.

printf is a function of library C

now, you can do it with t.c_str(), but it's not very c++ compliant.
Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Sep 14 '06 #5
Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?
I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.

Stephane
Sep 14 '06 #6
Stephane Wirtel wrote:
>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.
printf is C, but it's also C++. Does the fact that it's part of C
somehow pollute it? Do you also refuse to use sin, cos, etc. because
they're C?

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Sep 14 '06 #7
printf is C, but it's also C++. Does the fact that it's part of C
somehow pollute it? Do you also refuse to use sin, cos, etc. because
they're C?
You are right, sorry for my previous answer.
Sep 14 '06 #8
Pete Becker wrote:
Stephane Wirtel wrote:
>>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.

printf is C, but it's also C++. Does the fact that it's part of C
somehow pollute it?
To some degree, it does: you are loosing a bit of typesafety by using the
printf() family. Otherwise, the compiler would have complained about the
OPs attempt to pass a std::string. This relates to their C heritage in that
strict typing is not that much of an issue in C (after all C does not use
type information for overload resolution and templates).

Besides, "pollute" is a loaded term and has a non-technical aspect to its
meaning. In that aesthetical sense, printf() clearly pollutes a program --
at least in my eyes :)
Do you also refuse to use sin, cos, etc. because they're C?
Nope, those are typesafe despite coming from C. (However, in my eyes these
also polute a program but for a different reason: you are calling a
function with a somewhat ill-defined contract: the standard says that
sin(x) computes the sin of x, which is a lie for almost all values of x.
What it actually computes is some unspecified approximation to the sin of
x. Thus, precision guarantess become a portability issue.)
Best

Kai-Uwe Bux
Sep 14 '06 #9
Kai-Uwe Bux wrote:
Pete Becker wrote:
>Stephane Wirtel wrote:
>>>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?
I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.
printf is C, but it's also C++. Does the fact that it's part of C
somehow pollute it?

To some degree, it does: you are loosing a bit of typesafety by using the
printf() family.
That's different. There are reasons to choose C++ streams, and reasons
to choose printf. There is no reason for a blanket refusal to use C,
which is what I was replying to.
>
Besides, "pollute" is a loaded term and has a non-technical aspect to its
meaning.
Yes, that's why I used it.
In that aesthetical sense, printf() clearly pollutes a program --
at least in my eyes :)
But, again, this wasn't about the merits of printf, but of C in general.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Sep 14 '06 #10

"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ee**********@murdoch.acc.Virginia.EDU...
Pete Becker wrote:
>Stephane Wirtel wrote:
>>>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.

printf is C, but it's also C++. Does the fact that it's part of C
somehow pollute it?

To some degree, it does: you are loosing a bit of typesafety by using the
printf() family. Otherwise, the compiler would have complained about the
OPs attempt to pass a std::string. This relates to their C heritage in
that
strict typing is not that much of an issue in C (after all C does not use
type information for overload resolution and templates).

Besides, "pollute" is a loaded term and has a non-technical aspect to its
meaning. In that aesthetical sense, printf() clearly pollutes a program --
at least in my eyes :)
>Do you also refuse to use sin, cos, etc. because they're C?

Nope, those are typesafe despite coming from C. (However, in my eyes these
also polute a program but for a different reason: you are calling a
function with a somewhat ill-defined contract: the standard says that
sin(x) computes the sin of x, which is a lie for almost all values of x.
What it actually computes is some unspecified approximation to the sin of
x. Thus, precision guarantess become a portability issue.)

Best

Kai-Uwe Bux
So I presume you also avoid using float or double, since they, too,
obviously "pollute" your program with "somewhat ill-defined" values?

--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
Sep 14 '06 #11
Fred Kleinschmidt wrote:
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ee**********@murdoch.acc.Virginia.EDU...
>Pete Becker wrote:
>>Do you also refuse to use sin, cos, etc. because they're C?
Nope, those are typesafe despite coming from C. (However, in my eyes these
also polute a program but for a different reason: you are calling a
function with a somewhat ill-defined contract: the standard says that
sin(x) computes the sin of x, which is a lie for almost all values of x.
What it actually computes is some unspecified approximation to the sin of
x. Thus, precision guarantess become a portability issue.)
I believe the standard says that sin(x) computes the sine of x to some
implementation-defined precision, which is true. In practice, every
compiler that I've seen uses IEEE 784 floating-point numbers, but your
compiler's documentation should tell you what representation is used, so
there should be no surprises.
So I presume you also avoid using float or double, since they, too,
obviously "pollute" your program with "somewhat ill-defined" values?
I agree that the above argument is rather specious, but it doesn't
negate the overall point that I think this discussion is about. Namely,
that there is often a "C++ Way" of doing things that supersedes the
older "C Way" of doing things. The C standard (C90, I believe) is
indeed part of the C++ standard, so using stdio is perfectly valid C++.
Personally, I feel that it's better to use the "C++ Way" of doing
things (iostreams, in this example) when writing C++ code, unless
there's a good reason for it. I think most C++ programmers would agree
with me.

Nate
Sep 14 '06 #12
Nate Barney wrote:
>
I believe the standard says that sin(x) computes the sine of x to some
implementation-defined precision, which is true.
The precision of the computation of sin is not specified, nor is it
implementation-defined.
In practice, every
compiler that I've seen uses IEEE 784 floating-point numbers, but your
compiler's documentation should tell you what representation is used, so
there should be no surprises.
That's two different things. IEE 754 tells you (if I remember correctly)
the minimum number of bits in the significand of a float and of a
double, as well as the minimum number of bits in the exponent. That, in
turn, tells you the maximum precision and range that you can rely on in
portable code. Results of floating-point computations often lose low
bits, so turn out to be less precise than the representation supports
and, often, less precise than a more careful implementation of that same
computation would be. For example, Dinkumware spent most of a year
implementing the special math functions in TR1, burning thousands of
hours of computer time checking results and revising algorithms. The
resulting functions are far better than anything else that's available.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Sep 14 '06 #13

Kai-Uwe Bux wrote:
Pete Becker wrote:
Stephane Wirtel wrote:
>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.
printf is C, but it's also C++. Does the fact that it's part of C
somehow pollute it?

To some degree, it does: you are loosing a bit of typesafety by using the
printf() family. Otherwise, the compiler would have complained about the
OPs attempt to pass a std::string. This relates to their C heritage in that
strict typing is not that much of an issue in C (after all C does not use
type information for overload resolution and templates).
Unfortunately, there is standard replacement for the formatting
functionality found in the printf family. The stream formatting
mechanisms are quite limited.

Sep 14 '06 #14
Fred Kleinschmidt wrote:
>
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ee**********@murdoch.acc.Virginia.EDU...
>Pete Becker wrote:
[snip]
>>Do you also refuse to use sin, cos, etc. because they're C?

Nope, those are typesafe despite coming from C. (However, in my eyes
these also polute a program but for a different reason: you are calling a
function with a somewhat ill-defined contract: the standard says that
sin(x) computes the sin of x, which is a lie for almost all values of x.
What it actually computes is some unspecified approximation to the sin of
x. Thus, precision guarantess become a portability issue.)
[snip]
>
So I presume you also avoid using float or double, since they, too,
obviously "pollute" your program with "somewhat ill-defined" values?
The contracts for double and float are way better defined: through
std::numeric_limits<you can investigate the precision of the built-in
floating point types, e.g., via epsilon. However, there is no standard way
to obtain assurances about the accuracy of sin() or cos().
Best

Kai-Uwe Bux
Sep 14 '06 #15
To some degree, it does: you are loosing a bit of typesafety by using the
printf() family. Otherwise, the compiler would have complained about the
OPs attempt to pass a std::string. This relates to their C heritage in that
strict typing is not that much of an issue in C (after all C does not use
type information for overload resolution and templates).
Using things like printf() doesn't suddenly transform your program back
into C. It's still a C++ program, it's just using a function that used
to exist in C. One could argue that since it's C++, you should use the
more "modern" cout method, but cout is no more a feature of C++ than
printf(), it just so happens that printf() used to exist in C, and
people thought up cout after they thought up printf(). Still, there is
nothing else as flexible as printf() in C++.

Besides, I never liked the "cout << foo << bar << endl" style syntax
anyway, it doesn't make sense. The function call form for a printing
function is more readable, and more easily understood.

Sep 15 '06 #16
microx wrote:
>To some degree, it does: you are loosing a bit of typesafety by using the
printf() family. Otherwise, the compiler would have complained about the
OPs attempt to pass a std::string. This relates to their C heritage in
that strict typing is not that much of an issue in C (after all C does
not use type information for overload resolution and templates).

Using things like printf() doesn't suddenly transform your program back
into C. It's still a C++ program, it's just using a function that used
to exist in C.
So far, we are in agreement; and I think you are not contradicting anything
I claimed.
One could argue that since it's C++, you should use the
more "modern" cout method, but cout is no more a feature of C++ than
printf(), it just so happens that printf() used to exist in C, and
people thought up cout after they thought up printf(). Still, there is
nothing else as flexible as printf() in C++.
I never said what you "should" do or not. I just said that using the
printf() family has certain drawbacks. These drawbacks are not unrelated to
those functions coming from C.
>Still, there is nothing else as flexible as printf() in C++.
It depends on what you mean by flexible: you can overload operator>and
operator<< for your own classes. In my book, that makes those tools far
more flexible than the printf() family where you cannot introduce new
formating options to accommodate for user defined types.

Besides, I never liked the "cout << foo << bar << endl" style syntax
anyway, it doesn't make sense. The function call form for a printing
function is more readable, and more easily understood.
That is very much a personal or cultural thing and depends on what you are
used to. I find the printf() family harder to use since those functions
essentially implement an auxiliary formating language, which is far too
terse for me. I prefer a more verbose style. But that is entirely a matter
of style and taste. The technical differences lies in type-safety and
support for user defined types. In this regard, printf() looses to
operator<<.
Best

Kai-Uwe Bux
Sep 15 '06 #17
Pete Becker wrote:
Stephane Wirtel wrote:
>>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.

printf is C, but it's also C++.
Well, it's not very *idiomatic* C++, given the existence of iostreams.

--
Mike Smith
Sep 19 '06 #18
Mike Smith wrote:
Pete Becker wrote:
>Stephane Wirtel wrote:
>>>Code that uses it is well-formed and portable, so "compliant" here must
mean something else. Care to elaborate?

I don't want to use C and C++ in the same source, it's C (printf, libc)
or C++ (std::cout, std::string, STL, ...) and not both.

printf is C, but it's also C++.

Well, it's not very *idiomatic* C++, given the existence of iostreams.
It's idiomatic C++ if it's simpler to do the job with printf than it is
with iostreams.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Sep 19 '06 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Tony Murphy | last post by:
I've got an application that sends emails (not spam!). The application reads a template file (html/text) into a string, the string is processed and placeholders filled in as appropiate. I call a...
11
by: Grumble | last post by:
Hello, I have the following structure: struct foo { char *format; /* format string to be used with printf() */ int nparm; /* number of %d specifiers in the format string */ /* 0 <= nparm <=...
4
by: ben | last post by:
why is it, in the below code, when there's a printf statement (the one commented with /* ****** */) the final for loop prints out fine, but without the commented with stars printf statement...
7
by: sunfiresg | last post by:
During an interview, I am asked to answer a question: Printf is a major formatted output function provided by the standard C library. Printf accepts a formatting string followed by a various...
4
by: sushant | last post by:
hi why do we use '&' operator in scanf like scanf("%d", &x); but why not in printf() like printf("%d" , x); thnx in advance sushant
12
by: drM | last post by:
I have looked at the faq and queried the archives, but cannot seem to be able to get this to work. It's the usual factorial recursive function, but that is not the problem. It hangs after the user...
7
by: teachtiro | last post by:
Hi, 'C' says \ is the escape character to be used when characters are to be interpreted in an uncommon sense, e.g. \t usage in printf(), but for printing % through printf(), i have read that %%...
36
by: Debaser | last post by:
I've recently read in one of my old C books that puts() is a better function call with regard to performance than printf() in the following situation: puts("Some random text"); vs. ...
3
by: google | last post by:
Consider the following code: char str; char str2; strcpy(str, "%alfa% %beta% d%100%d %gamma% %delta%"); printf("printf: "); printf("1%s2", str); printf("\nsprintf: "); sprintf(str2, "1%s2",...
43
by: Jrdman | last post by:
someone has an idea on how the printf function is programmed ?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.