473,473 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Using printf on char array

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[i]);
}
}

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.
Jul 19 '05 #1
11 55469
WW
Pontus F wrote:
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[i]);
}
}

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.

--
WW aka Attila
Jul 19 '05 #2
Pontus F wrote:

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>
#include <string.h>

void printText(char c[]){
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf(c[i]);
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
Jul 19 '05 #3
WW wrote:
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
Jul 19 '05 #4
WW
Default User wrote:
WW wrote:
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.


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. :-(

--
WW aka Attila
Jul 19 '05 #5
Pontus F <--> wrote in message news:<9q********************************@4ax.com>. ..
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[i]);
}
}

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[i];

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
Jul 19 '05 #6
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" <wo***@freemail.hu> skrev i meddelandet
news:bm**********@phys-news1.kolumbus.fi...
Pontus F wrote:
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[i]);
}
}

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.

--
WW aka Attila

Jul 19 '05 #7
Pontus F wrote:

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 <string>.
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
Jul 19 '05 #8
Default User wrote:
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
Jul 19 '05 #9

"Default User" <fi********@boeing.com.invalid> skrev i meddelandet
news:3F***************@boeing.com.invalid...
Pontus F wrote:

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.


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.

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.


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.
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.


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
Jul 19 '05 #10


Pontus F wrote:

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.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #11
"Pontus F" <.> wrote in message news:<3f**********************@news.astraweb.com>. ..
"Default User" <fi********@boeing.com.invalid> skrev i meddelandet
news:3F***************@boeing.com.invalid...
Pontus F wrote:

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.


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.

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.


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
Jul 19 '05 #12

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

Similar topics

2
by: Goran | last post by:
Hi! I need to convert from a unsigned char array to a float. I don't think i get the right results in the program below. unsigned char array1 = { 0xde, 0xc2, 0x44, 0x23}; //I'm not sure in...
11
by: Walter Dnes (delete the 'z' to get my real address | last post by:
I've noticed a few threads (full of sound and fury, signifying nothing) here recently about allocation of large memory blocks. I'm about to start on a personal pet project where I'll be using...
7
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store...
15
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
13
by: Superman859 | last post by:
Hello everyone. Heads up - c++ syntax is killing me. I do quite well in creating a Java program with very few syntax errors, but I get them all over the place in c++. The smallest little things...
2
by: FlorinBr | last post by:
Hello! I am trying to initialize a lookup table, which consists of characters. The problem is that I need the characters in hexadecimal. So, I tried the following: <code> #define UNSUPPORTED...
2
by: nagesh0280 | last post by:
Hi experts, I'm from a Verilog HDL background and trying to learn C. There are a lot of similarities between Verilog and C but the concept of char arrays and strings has me confused. I'd...
0
by: sam.barker0 | last post by:
Hi, How can I convert a unsigned char array1 which holds the ipaddress, into a string I am using a char array to insert the '.' between the bytes. I am using a char array because then I can...
2
by: Lohith r | last post by:
Hi Friends, I have a serious and irritating problem, please help mdContext->digest is an unsigned char Array with hexadecimal values so for (i = 0; i < 16; i++) printf ("%02x",...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
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...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.