首页 > 解决方案 > '\n' 在 memset (C) 之后保存在数组中

问题描述

我读取字符直到 '\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

标签: cscanfmemset

解决方案


您在代码中有多个问题。他们之中有一些是

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

  2. 您从未检查调用的返回值scanf()以确保成功。

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


推荐阅读