Using printf on char array

P

Pontus F

Hi I am learning C++ and I'm still trying to get a grip of pointers
and other C/C++ concepts. I would appreciate if somebody could explain
what's wrong with this code:

---begin code block---

#include "stdio.h"
#include "string.h"

void printText(char c[]){
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf(c);
}
}

void main()
{
char b[2];
b[0] = 'a';
b[1] = 'b';
while(1){
printText(b);
}
}
---end code block---

As you can see, what I'm trying to do is to make a function which
accepts a char array and then prints the entire array, char by char.
This should be trivial, right? I feel like I've missed some major
concept here :) Enlighten me please :)

BTW this is what the compiler throws at me:
error C2664: 'printf' : cannot convert parameter 1 from 'char' to
'const char *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast


regards
Pontus F.
 
W

WW

Pontus said:
Hi I am learning C++ and I'm still trying to get a grip of pointers
and other C/C++ concepts. I would appreciate if somebody could explain
what's wrong with this code:

It is not indented. :) Please before you post code to newsgroups change
TABs to (two) spaces. Newsreaders eat TABs on the beginning of lines. :-(
---begin code block---

#include "stdio.h"
#include "string.h"

void printText(char c[]){
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf(c);
}
}

void main()
{
char b[2];
b[0] = 'a';
b[1] = 'b';
while(1){
printText(b);
}
}
---end code block---

As you can see, what I'm trying to do is to make a function which
accepts a char array and then prints the entire array, char by char.
This should be trivial, right? I feel like I've missed some major
concept here :) Enlighten me please :)

BTW this is what the compiler throws at me:
error C2664: 'printf' : cannot convert parameter 1 from 'char' to
'const char *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast


You need to learn printf! One tutorial, which (with a fast glance) seems to
be good is http://cplus.about.com/library/weekly/aa032302a.htm

int printf(const char *format, arg1, arg2, arg3, ......);

You did not give the format string, but the argument you want to print!

I could give you the solution, but I will be a stinker. Please read the
tutorial (it is a short page) and get back here if you could not figure out
what to do. I think if I just tell you what to type there you won't learn
anything from it.
 
D

Default User

Pontus said:
Hi I am learning C++ and I'm still trying to get a grip of pointers
and other C/C++ concepts.

What you have is pretty much C, although it will work as C++. Pick a
language.
I would appreciate if somebody could explain
what's wrong with this code:

---begin code block---

#include "stdio.h"
#include "string.h"

#include <stdio.h>
void printText(char c[]){
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf(c);


Get a book, then look up the signature of the printf() function. It
requires a char* as its first argument. It's also pointless to waste all
this code printing a string. There are printf() formats for that.
}
}

void main()

main() returns int ALWAYS.
{
char b[2];
b[0] = 'a';
b[1] = 'b';
while(1){
printText(b);

Your function above was taking strlen() of the char buffer, which
requires it to be a null-terminated C-style string. You don't have that.
Your program will not work. You could pass in the size, but you are
better off with strings.

What are you trying to accomplish?
As you can see, what I'm trying to do is to make a function which
accepts a char array and then prints the entire array, char by char.
This should be trivial, right? I feel like I've missed some major
concept here :) Enlighten me please :)

See above.



Brian Rodenborn
 
D

Default User

WW said:
It is not indented. :) Please before you post code to newsgroups change
TABs to (two) spaces. Newsreaders eat TABs on the beginning of lines. :-(


Some newsreaders. It was indented for me.



Brian Rodenborn
 
W

WW

Default said:
Some newsreaders. It was indented for me.

Yeah. I was very surprised that (for example) the one coming with KDE has
this same "feature". I wanted to look at the RFCs, but after the reference
to the 55th other RFC I gave up. :-(
 
R

Ron Samuel Klatchko

Pontus F said:
Hi I am learning C++ and I'm still trying to get a grip of pointers
and other C/C++ concepts. I would appreciate if somebody could explain
what's wrong with this code:

void printText(char c[]) {
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf(c);
}
}

As you can see, what I'm trying to do is to make a function which
accepts a char array and then prints the entire array, char by char.
This should be trivial, right? I feel like I've missed some major
concept here :) Enlighten me please :)


Well, since you're posting on comp.lang.c++, my first answer is to say
don't bother with the C compatible formatting library. It's neither
type safe nor extensible so it's a pain to use.

Instead you should look into using C++ iostreams. Instead of worry
abouting printf format strings, all you would have to do is convert
the printf to:

cout << c;

and the compiler will make sure the object is properly displayed.

But while C++ iostreams are easier to use, I have never found a good
way to integrate i18ned message catalogs with them, so another answer
is that sticking with C output functions are the way to go.

printf() is a very powerful command. It can take multiple arguments
and combine them according to a format string. This format string
tells how to interpret the arguments and any special instructions
(such as print an integer right justified to 8 spaces with leading
0's, etc). The full description of printf formatting strings is quite
large so I'm not going to attempt to summarize for you.

But for simply outputting strings or characters, printf is way
overkill. If you want to learn that family of functions, you should
also learn about putc(), fputc(), puts() and fputs(). Any decent C
book should cover those for you.

samuel
 
P

Pontus F

Thanks to everyone who replied. I realize that printf was overkill for what
i was trying to do :). Anyway after reading up on how to use the
cin/cout/printf functions i rewrote the code into this (now correctly
indented, sorry about that in the original post):

#include <iostream>
#include <string>
using namespace std;

void printText(char c[]){
cout << c << "\n";
}

int main() {
char myString[20];
while(1){
cout << "Text to print: ";
cin >> myString;
printText(myString);
}
return 0;
}

Which works alot better :)
Thanks again
Pontus F.


WW said:
Pontus said:
Hi I am learning C++ and I'm still trying to get a grip of pointers
and other C/C++ concepts. I would appreciate if somebody could explain
what's wrong with this code:

It is not indented. :) Please before you post code to newsgroups change
TABs to (two) spaces. Newsreaders eat TABs on the beginning of lines. :-(
---begin code block---

#include "stdio.h"
#include "string.h"

void printText(char c[]){
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf(c);
}
}

void main()
{
char b[2];
b[0] = 'a';
b[1] = 'b';
while(1){
printText(b);
}
}
---end code block---

As you can see, what I'm trying to do is to make a function which
accepts a char array and then prints the entire array, char by char.
This should be trivial, right? I feel like I've missed some major
concept here :) Enlighten me please :)

BTW this is what the compiler throws at me:
error C2664: 'printf' : cannot convert parameter 1 from 'char' to
'const char *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast


You need to learn printf! One tutorial, which (with a fast glance) seems to
be good is http://cplus.about.com/library/weekly/aa032302a.htm

int printf(const char *format, arg1, arg2, arg3, ......);

You did not give the format string, but the argument you want to print!

I could give you the solution, but I will be a stinker. Please read the
tutorial (it is a short page) and get back here if you could not figure out
what to do. I think if I just tell you what to type there you won't learn
anything from it.
 
D

Default User

Pontus said:
Thanks to everyone who replied. I realize that printf was overkill for what
i was trying to do :). Anyway after reading up on how to use the
cin/cout/printf functions i rewrote the code into this (now correctly
indented, sorry about that in the original post):

Don't top-post. Your replies belong following properly trimmed quotes.
#include <iostream>
#include <string>
using namespace std;

This looks better.
void printText(char c[]){
cout << c << "\n";
}

This is not quite the same. You are putting a newline after every
character output. Doesn't sound like what you really want, but maybe it
is.
int main() {
char myString[20];

Hmmm. You include the <string> header, but then use char buffers. You
don't end up using anything from said:
while(1){
cout << "Text to print: ";
cin >> myString;

Here you have no overflow protection if someone enters more than 19
characters. Also, cin delimits input by white space, so if the entry at
the console is:

Hello World!

Then only the "Hello" would be processed.
printText(myString);

At least the UB from an unterminated char buffer is eliminated.
}
return 0;
}

Which works alot better :)

Somewhat, but it's still brittle. I'd use std::string in place of that
char buffer at your stage. That eliminates one big hole. Then use
getline() read in an entire line rather than a word.

What book are you using?



Brian Rodenborn
 
D

Default User

Default said:
void printText(char c[]){
cout << c << "\n";
}

This is not quite the same. You are putting a newline after every
character output. Doesn't sound like what you really want, but maybe it
is.

Sorry, misread that. Never mind.



Brian Rodenborn
 
P

Pontus F

Default User said:
Don't top-post. Your replies belong following properly trimmed quotes.

My bad, sorry.
#include <iostream>
#include <string>
using namespace std;

This looks better.
void printText(char c[]){
cout << c << "\n";
}

This is not quite the same. You are putting a newline after every
character output. Doesn't sound like what you really want, but maybe it
is.
int main() {
char myString[20];

Hmmm. You include the <string> header, but then use char buffers. You
don't end up using anything from <string>.

sorry I just cut out the part of the code that is relevant, but forgot that
#include.
I use string in another part of my program.

Here you have no overflow protection if someone enters more than 19
characters. Also, cin delimits input by white space, so if the entry at
the console is:

Hello World!

Then only the "Hello" would be processed.

Hmm yes that's true. I didn't notice that since I've only tried to output
single
words so far. BTW, the program is supposed to output text via the parallel
port to a vacuum flourescent display (VFD). The program is now fully
functional :). Oh, if I enter more than 20 chars, nothing in particular
happens.
Doesn't my program care if I overflow an array? Is the array size perhaps
dynamically redefined automagically?
The text output to the VFD isn't affected by this though, I truncate the
char array
in another part of the program.
At least the UB from an unterminated char buffer is eliminated.


Somewhat, but it's still brittle. I'd use std::string in place of that
char buffer at your stage. That eliminates one big hole. Then use
getline() read in an entire line rather than a word.
Thanks

What book are you using?

I started with "C++ for dummies" by Stephen Davis which wasn't very
good IMHO. Perhaps I'm not the right kind of dummy ;).
Now reading "Thinking in C++" by Bruce Eckel instead, I like this
one a lot better.

Pontus F
 
K

Karl Heinz Buchegger

Pontus said:
words so far. BTW, the program is supposed to output text via the parallel
port to a vacuum flourescent display (VFD). The program is now fully
functional :). Oh, if I enter more than 20 chars, nothing in particular
happens.

Oh, strange things happen in your program if you do this. But at the
moment you are just unlucky because you can't see any symptoms. If
you are lucky, then the program would crash immediatly.
Doesn't my program care if I overflow an array? Is the array size perhaps
dynamically redefined automagically?

If you overflow an array, then your program writes to some memory. If the
content of that memory is vital for the functioning of your program
(it could eg. the programs code itself that you overwrite) or not,
depends on circumstances outside of your control. If the compiler
didn't put something else after the array and the memory was (again:
per accident) reserved for your program by the operating system then
your program might get away with it. But nevertheless it is still
a bug, hope you have read this between the lines. A bug doesn't
necessarilly manifest itself with fire and smoke. Those are the bugs
where the programmer has luck. If the programmer is unlucky, then
the bug is delivered unnoticed, the program seems to work but breaks
at some unwanted times, eg. when trying to save the world by shutting
down a malfunctioning nuclear power plant. This would be a perfect
timing for a pending bug to maxime damage by just crashing the computer.
 
R

Roxann Higuera

Pontus F said:
Default User said:
Don't top-post. Your replies belong following properly trimmed quotes.

My bad, sorry.
#include <iostream>
#include <string>
using namespace std;

This looks better.
void printText(char c[]){
cout << c << "\n";
}

This is not quite the same. You are putting a newline after every
character output. Doesn't sound like what you really want, but maybe it
is.
int main() {
char myString[20];

Hmmm. You include the <string> header, but then use char buffers. You
don't end up using anything from <string>.

sorry I just cut out the part of the code that is relevant, but forgot that
#include.
I use string in another part of my program.

Here you have no overflow protection if someone enters more than 19
characters. Also, cin delimits input by white space, so if the entry at
the console is:

Hello World!

Then only the "Hello" would be processed.

Hmm yes that's true. I didn't notice that since I've only tried to output
single
words so far. BTW, the program is supposed to output text via the parallel
port to a vacuum flourescent display (VFD). The program is now fully
functional :). Oh, if I enter more than 20 chars, nothing in particular
happens.
Doesn't my program care if I overflow an array? Is the array size perhaps
dynamically redefined automagically?
The text output to the VFD isn't affected by this though, I truncate the
char array
in another part of the program.

Just because you don't see the effects of the overflow here doesn't
mean the code is OK. Sure, it may work as a stand-alone program. But
what if this same code is later used as a function in another program?
Maybe the overflow won't be so harmless then. The fact that you had
to truncate should have told you something.

Also, your original code had another bug -- the character array was
defined to have 2 elements, and both of those elements were assigned
non-zero values. Your string had no terminator! Because of this, you
could not have properly calculated its length in the printText
function. If you got a length of 2, you were lucky. While
technically the character array did not overflow, it could well behave
as if it had.

Either of these errors can result in bugs that can take hours, days,
or even months to find. It's akin to finding a needle in a haystack.
Pay attention to the details at the outset, and you will save a lot of
grief for yourself or someone else on your programming team. I know
because I've had to find bugs like these buried in mammoth projects
with code created by many programmers.

Roxann Higuera
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top