Reputation: 2346
Ok, i'm a student in his first experiences with programmaing so be kind ;) this is the correct code to print "n" times a string on screen...
#include <stdio.h>
#include <string.h>
#define MAX 80+1+1 /* 80+\n+\0 */
int main(void)
{
char message[MAX];
int i, n;
/* input phase */
printf("Input message: ");
i = 0;
do {
scanf("%c", &message[i]);
} while (message[i++] != '\n');
message[i] = '\0';
printf("Number of repetitions: ");
scanf("%d", &n);
/* output phase */
for (i=0; i<n; i++) {
printf("%s", message);
}
return 0;
}
why in the do-while form he needs to check if message[i++] != '\n' and not just message[i] != '\n'??
Upvotes: 0
Views: 93
Reputation: 1668
The do { ... } while(...)
loop in your code reads characters one at a time and stores them in message
. The index of the next character is one more that the index of the previous character, that's why we should increase index variable i
after the current character is stored. The algorithm is:
message[i]
.'\n'
, exit.i
and goto 1.The expression message[i++]
increments i
after it was used as an index into message
, so that next time we will look at the next character in the string. So, while (message[i++] != '\n')
combines steps 2 and 3.
The same in for
-loop:
int i;
for (i = 0; scanf("%c", &message[i]) && message[i] != '\n'; ++i);
But as @unwind pointed, it's better not to use char-by-char input.
Upvotes: 1
Reputation: 399763
The proper way to write that input loop is, in my opinion, something along the lines of:
fgets(message, sizeof message, stdin);
in other words, don't use a character-by-character loop, just use the standard library's function that reads a string terminated by newline and be done.
Upvotes: 3