简体   繁体   English

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

[英]'\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.我读取字符直到 '\n',将它们转换为 int 并对数字求和,直到结果只有一位。

I can't use mod or.我不能使用 mod 或。

The first run went well, but the second one keep running and not waiting to \n.第一次运行顺利,但第二次继续运行,没有等到\n。

any reason for keeping the '\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 TIA

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. c是一个char ,你必须使用%c转换说明符。

  2. You never checked for the return value of scanf() calls to ensure success.您从未检查scanf()调用的返回值以确保成功。

  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 .任何现有字符,包括缓冲区中已经存在的换行符 ( '\n' ) 都将被视为%c的有效输入。 You need to clear the buffer before you read a character input.您需要在读取字符输入之前清除缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM