Pointers not allowed to used iostream

  • Thread starter Thread starter ZakAttk1
  • Start date Start date
  • Tags Tags
    Pointers
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
ZakAttk1
Messages
7
Reaction score
0
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.
 
Physics news on Phys.org


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
 


So to mark the end of the string I'll have to do something with *word = '\0'.
Is that relevant?
 


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


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