'\ n'在内存集(C)之后保存在数组中

问题描述 投票:0回答:1

我读字符直到'\ n',将它们转换为int并将数字求和,直到结果只有一位。

我不能使用mod或。

第一次运行顺利,但是第二次继续运行,不等到\ n。

保留'\ 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

c scanf memset
1个回答
1
投票

您在代码中有多个问题。其中一些是

  1. scanf("%s", &c);是错误的。 cchar,必须为此使用%c转换说明符。

  2. 您从未检查过return value of scanf()呼叫以确保成功。

  3. 扫描字符输入时,您没有清除任何现有输入的缓冲区。缓冲区中已经存在的任何现有字符,包括换行符(scanf()),都将被视为'\n'的有效输入。在读取字符输入之前,需要清除缓冲区。

© www.soinside.com 2019 - 2024. All rights reserved.