Using printf on char array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pontus F

    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_cas t, C-style cast or function-style cast


    regards
    Pontus F.
  • WW

    #2
    Re: Using printf on char array

    Pontus F wrote:[color=blue]
    > 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:[/color]

    It is not indented. :-) Please before you post code to newsgroups change
    TABs to (two) spaces. Newsreaders eat TABs on the beginning of lines. :-(
    [color=blue]
    > ---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_cas t, C-style cast or function-style cast[/color]

    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


    Comment

    • Default User

      #3
      Re: Using printf on char array

      Pontus F wrote:[color=blue]
      >
      > Hi I am learning C++ and I'm still trying to get a grip of pointers
      > and other C/C++ concepts.[/color]

      What you have is pretty much C, although it will work as C++. Pick a
      language.
      [color=blue]
      > I would appreciate if somebody could explain
      > what's wrong with this code:
      >
      > ---begin code block---
      >
      > #include "stdio.h"
      > #include "string.h"[/color]

      #include <stdio.h>
      #include <string.h>

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

      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.
      [color=blue]
      > }
      > }
      >
      > void main()[/color]

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

      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?
      [color=blue]
      > 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 :)[/color]

      See above.



      Brian Rodenborn

      Comment

      • Default User

        #4
        Re: Using printf on char array

        WW wrote:
        [color=blue]
        > It is not indented. :-) Please before you post code to newsgroups change
        > TABs to (two) spaces. Newsreaders eat TABs on the beginning of lines. :-([/color]


        Some newsreaders. It was indented for me.



        Brian Rodenborn

        Comment

        • WW

          #5
          Re: Using printf on char array

          Default User wrote:[color=blue]
          > WW wrote:
          >[color=green]
          >> It is not indented. :-) Please before you post code to newsgroups
          >> change TABs to (two) spaces. Newsreaders eat TABs on the beginning
          >> of lines. :-([/color]
          >
          > Some newsreaders. It was indented for me.[/color]

          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


          Comment

          • Ron Samuel Klatchko

            #6
            Re: Using printf on char array

            Pontus F <--> wrote in message news:<9q8movol7 d0mi2327ah0bcvv emjt832pdu@4ax. com>...[color=blue]
            > 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 :)[/color]

            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

            Comment

            • Pontus F

              #7
              Re: Using printf on char array

              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(myStr ing);
              }
              return 0;
              }

              Which works alot better :)
              Thanks again
              Pontus F.


              "WW" <wolof@freemail .hu> skrev i meddelandet
              news:bmfa4l$dv2 $1@phys-news1.kolumbus. fi...[color=blue]
              > Pontus F wrote:[color=green]
              > > 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:[/color]
              >
              > It is not indented. :-) Please before you post code to newsgroups change
              > TABs to (two) spaces. Newsreaders eat TABs on the beginning of lines. :-(
              >[color=green]
              > > ---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_cas t, C-style cast or function-style cast[/color]
              >
              > You need to learn printf! One tutorial, which (with a fast glance) seems[/color]
              to[color=blue]
              > 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[/color]
              out[color=blue]
              > what to do. I think if I just tell you what to type there you won't learn
              > anything from it.
              >
              > --
              > WW aka Attila
              >
              >[/color]


              Comment

              • Default User

                #8
                Re: Using printf on char array

                Pontus F wrote:[color=blue]
                >
                > 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):[/color]

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

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

                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.
                [color=blue]
                > int main() {
                > char myString[20];[/color]

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

                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.
                [color=blue]
                > printText(myStr ing);[/color]

                At least the UB from an unterminated char buffer is eliminated.
                [color=blue]
                > }
                > return 0;
                > }
                >
                > Which works alot better :)[/color]

                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

                Comment

                • Default User

                  #9
                  Re: Using printf on char array

                  Default User wrote:
                  [color=blue][color=green]
                  > > void printText(char c[]){
                  > > cout << c << "\n";
                  > > }[/color]
                  >
                  > 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.[/color]

                  Sorry, misread that. Never mind.



                  Brian Rodenborn

                  Comment

                  • Pontus F

                    #10
                    Re: Using printf on char array


                    "Default User" <first.last@boe ing.com.invalid > skrev i meddelandet
                    news:3F8C2A8C.D B397B8F@boeing. com.invalid...[color=blue]
                    > Pontus F wrote:[color=green]
                    > >
                    > > Thanks to everyone who replied. I realize that printf was overkill for[/color][/color]
                    what[color=blue][color=green]
                    > > 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):[/color]
                    >
                    > Don't top-post. Your replies belong following properly trimmed quotes.[/color]

                    My bad, sorry.
                    [color=blue][color=green]
                    > > #include <iostream>
                    > > #include <string>
                    > > using namespace std;[/color]
                    >
                    > This looks better.
                    >[color=green]
                    > > void printText(char c[]){
                    > > cout << c << "\n";
                    > > }[/color]
                    >
                    > 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.
                    >[color=green]
                    > > int main() {
                    > > char myString[20];[/color]
                    >
                    > Hmmm. You include the <string> header, but then use char buffers. You
                    > don't end up using anything from <string>.[/color]

                    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.

                    [color=blue][color=green]
                    > > while(1){
                    > > cout << "Text to print: ";
                    > > cin >> myString;[/color]
                    >
                    > 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.[/color]

                    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.
                    [color=blue][color=green]
                    > > printText(myStr ing);[/color]
                    >
                    > At least the UB from an unterminated char buffer is eliminated.
                    >[color=green]
                    > > }
                    > > return 0;
                    > > }
                    > >
                    > > Which works alot better :)[/color]
                    >
                    > 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.[/color]

                    Thanks
                    [color=blue]
                    > What book are you using?[/color]

                    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


                    Comment

                    • Karl Heinz Buchegger

                      #11
                      Re: Using printf on char array



                      Pontus F wrote:[color=blue]
                      >
                      > 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.[/color]

                      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.
                      [color=blue]
                      > Doesn't my program care if I overflow an array? Is the array size perhaps
                      > dynamically redefined automagically?[/color]

                      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
                      kbuchegg@gascad .at

                      Comment

                      • Roxann Higuera

                        #12
                        Re: Using printf on char array

                        "Pontus F" <.> wrote in message news:<3f8c6ef0$ 0$34378$c3e8da3 @news.astraweb. com>...[color=blue]
                        > "Default User" <first.last@boe ing.com.invalid > skrev i meddelandet
                        > news:3F8C2A8C.D B397B8F@boeing. com.invalid...[color=green]
                        > > Pontus F wrote:[color=darkred]
                        > > >
                        > > > Thanks to everyone who replied. I realize that printf was overkill for[/color][/color]
                        > what[color=green][color=darkred]
                        > > > 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):[/color]
                        > >
                        > > Don't top-post. Your replies belong following properly trimmed quotes.[/color]
                        >
                        > My bad, sorry.
                        >[color=green][color=darkred]
                        > > > #include <iostream>
                        > > > #include <string>
                        > > > using namespace std;[/color]
                        > >
                        > > This looks better.
                        > >[color=darkred]
                        > > > void printText(char c[]){
                        > > > cout << c << "\n";
                        > > > }[/color]
                        > >
                        > > 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.
                        > >[color=darkred]
                        > > > int main() {
                        > > > char myString[20];[/color]
                        > >
                        > > Hmmm. You include the <string> header, but then use char buffers. You
                        > > don't end up using anything from <string>.[/color]
                        >
                        > 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.
                        >
                        >[color=green][color=darkred]
                        > > > while(1){
                        > > > cout << "Text to print: ";
                        > > > cin >> myString;[/color]
                        > >
                        > > 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.[/color]
                        >
                        > 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.[/color]

                        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

                        Comment

                        Working...