Lc0rE
Lc0rE

Reputation: 2346

Issue on a do-while form in Strings

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

Answers (2)

Alex Bakulin
Alex Bakulin

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:

  1. Read the next character and store it in message[i].
  2. If this character is '\n', exit.
  3. Increase 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

unwind
unwind

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

Related Questions