Ricky
Ricky

Reputation: 7

Character Arrays using

I want to use scanf_s("%c\n", &arr[index]) to input once character at a time in a single line using for/while loop. I cannot figure out how to output the result. Below is the code.(I only want to use scanf statement. fgets way is easy.

printf("\nEnter the lowercase letters\n");
for (index = 0; index < size; index++)
{
    scanf_s("%c\n", &arr[index]);
    _getch();
}
printf("\nThanks"); 
for (index = 0; index < size; ++index)
{
    printf("%c/n", arr[index]);
}

It takes the input but exits out after thanks statement. I cannot figure out why. Although I have used a different method that works. It's just a variation I was trying.

Upvotes: 0

Views: 60

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753495

This code would probably work better:

int nchars;

printf("\nEnter the lowercase letters\n");
for (index = 0; index < size; index++)
{
    if (scanf_s("%c", &arr[index], 1) != 1)
        break;
}
printf("\nThanks\n");
nchars = index;  // Do not report on values that were not entered 
for (index = 0; index < nchars; ++index)
{
    printf("%c\n", arr[index]);
}

Note that when you use scanf_s() and the %c format (and %s and %[…]formats), it require a length as well as the pointer to the data storage location (two arguments for one conversion specification). This tells the function how much space there is available to store the value. Often, the length will not be 1; you'd use scanf_s("%s", buffer, sizeof(buffer)) to read a string.

It is a good idea to check the return value from scanf_s() every time you use it so that you know whether it worked or not.

You can add extra criteria for breaking the loop, such as if the code reads a newline.


I also noted some problems in the comments — the issues are fixed in the code above.

  • Why are you using _getch() when you're also scanning with scanf_s()? That's going to confuse the poor user who types abcd and sees only ac. The _getch() is eating the b and d.
  • Also, newline is \n not /n — the third printf() has that as a typo.
  • Using \n at the end of an interactive input format string is a bad idea; the user has to type something that's not a white space character after the input to get the scanf_s() to return.

Upvotes: 1

Spikatrix
Spikatrix

Reputation: 20244

Change

scanf_s("%c\n", &arr[index]);
_getch();

To

scanf_s(" %c", &arr[index], 1);

When scanning a character(%c) or string(%s) using scanf_s, you must supply an additional value as a parameter which indicates the amount of characters to be scanned.
The space before %c discards all whitespace characters(newlines, spaces etc) including none before scanning a non-whitespace character.

Also, the printf in the loop has /n instead of \n for a newline.

Upvotes: 1

Related Questions