Search code examples
cscanfmemset

'\n' saved in array after memset (C)


I read chars until '\n', convert them to int and sum the numbers until the result is only one digit.

I can't use mod or .

The first run went well, but the second one keep running and not waiting to \n.

any reason for keeping the '\n'?

#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;

while(1){
    printf("Enter 8 values(0-9) :\n");
    scanf("%[^\n]", str);   // Scan values to str untill \n

    for(i = 0;i < 8;i++){
        val = str[i]-48;    //convert from asci to int
        ans += val;
    }

    while(ans > 9){
        // itoa convert int to string, str(the input) is the buffer and 10 is the base
        itoa(ans,conv_str,10);
        ans = (conv_str[0]-48) + (conv_str[1]-48) ;
    }
    printf("the digit is:  %d", ans);

    printf("\ncontinue? (y/n)\n");
    scanf("%s", &c);
    if (c == 'n')
        break;
    memset(str, 0, sizeof(str));
}

return 0;
}

TIA


Solution

  • You have multiple problems in the code. Some of them are

    1. scanf("%s", &c); is wrong. c is a char, you must use %c conversion specifier for that.

    2. You never checked for the return value of scanf() calls to ensure success.

    3. While scanning for character input, you did not clear the buffer of any existing inputs. Any existing character, including a newline ('\n') already present in the buffer will be considered as a valid input for %c. You need to clear the buffer before you read a character input.