0

I tried to scan and print the characters of array using below code but input characters are not matching with output characters

#include <stdio.h>
int main() {
    char s[10];
    int i, n;
    printf("enter the value of n:\n");
    scanf("%d", &n);
    printf("start entering the characters:\n");
    for (i = 0; i < n; i++) {
        scanf("%c", &s[i]);
    }
    for (i = 0; i < n; i++) {
        printf("%c", s[i]);
    }
    return 0;
}

OUTPUT

enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)

Can anyone please clarify my doubt why is the output not matching with input

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
coder
  • 1
  • 1
  • can you please elaborate the answer – coder Jul 02 '22 at 17:17
  • @coder Your teacher has done you a disservice. Your teacher taught you about `scanf`, but did not reveal the [secret list of rules](https://stackoverflow.com/questions/72178518#72178652) for using it successfully. You just need to apply #11 on that list. – Steve Summit Jul 02 '22 at 17:23
  • @xing Ah, yes, true. – Ted Lyngmo Jul 02 '22 at 17:47
  • 3
    @TedLyngmo — see [The effect of trailing white space on a `scanf()` format string](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) and never again recommend a trailing space in a `scanf()` format string. (You might be able to get away with it if the input is never from the terminal (only from files, for example), but even then it isn't usually necessary or a good idea.) – Jonathan Leffler Jul 02 '22 at 18:19
  • 2
    @JonathanLeffler Promise! :-) – Ted Lyngmo Jul 02 '22 at 18:30

1 Answers1

0

Since you are wanting to read data into a character array with "scanf" you probably could just reference the string identifier instead and simplify things. Following are a few tweaks to your code that still inputs the data and prints it back out.

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

int main()
{
    char s[10];
    int i, n;
    printf("enter the value of n:\n");
    scanf("%d", &n);
    printf("start entering the characters:\n");

    scanf("%s", s);      /* In lieu of using a loop */

    if (strlen(s) < n)   /* Just in case less characters are entered than was noted */
        n = strlen(s);

    for (i = 0; i < n; i++)
    {
        printf("%c", s[i]);
    }

    printf("\n");

    return 0;
}

The program just scans in the complete string instead of a character at a time. Also, I included the "<string.h> file so as to use functions such as "strlen" (get the length of the string) to provide a bit more robustness to the code. Running the program netted the same character set that was entered.

:~/C_Programs/Console/InputOutput/bin/Release$ ./InputOutput 
enter the value of n:
7
start entering the characters:
ABCDEFG
ABCDEFG

You might give that a try.

Regards.

NoDakker
  • 3,390
  • 1
  • 10
  • 11