Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Pointers not allowed to used iostream

  1. Mar 31, 2009 #1
    I want to infinitely print a saying to the console but I am not allowed to used iostream.

    I am using the function putc. I understand I need to use an infinite loop. So far I have:

    int main()
    {
    char *word;
    word = &SAYING[0];

    while(true)
    {
    putc(*word, stdout);
    word ++;
    putc(*word, stdout);


    }


    return 0;


    However, it only prints the first 2 characters. I need to somehow write some code that automatically prints the saying without having to repeat:

    word ++;
    putc(*word, stdout);



    any advice on how to get started on the rest?
    Thanks.
     
  2. jcsd
  3. Mar 31, 2009 #2

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Re: pointers

    If you just increment the "word" pointer forever, you'll go past the end of the string and begin printing out random garbage. Your program will eventually crash.

    You need to detect that you've reached the end of the string (it will end with a null byte), and go back to the beginning.

    - Warren
     
  4. Mar 31, 2009 #3
    Re: pointers

    So to mark the end of the string I'll have to do something with *word = '\0'.
    Is that relevant?
     
  5. Mar 31, 2009 #4

    rcgldr

    User Avatar
    Homework Helper

    Re: pointers

    I'm guessing that "true" isn't defined, and you compiler is defaulting it to 0, which keeps the while loop from running. Try while(1), or better still while(*word != 0), and only use one instance of putc(*word), word++.
     
  6. Mar 31, 2009 #5
    Re: pointers

    If you want to print the sentence forever, you will need two while loops, one that repeatedly prints the same line, another detects the end of the sentence and go back to print the beginning.
    The pseudocode looks like the following:
    char saying[]=".....";
    char *ptr;
    while(true)
    {
    ptr=saying; // starts printing line
    while(*ptr!=end-of-string){putc(...); ptr++;}
    } // end of line, go back to pring another line
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Pointers not allowed to used iostream
  1. This pointer (Replies: 2)

  2. Use of pointers (Replies: 3)

Loading...