我读取字符直到“\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
最佳答案
您的代码中存在多个问题。其中一些是
scanf("%s", &c);
是错误的。c
是char
,您必须使用%c
转换说明符。您从未检查过 return value of
scanf()
调用以确保成功。扫描字符输入时,您没有清除任何现有输入的缓冲区。任何现有字符,包括缓冲区中已存在的换行符 (
'\n'
),都将被视为%c
的有效输入。在读取字符输入之前,您需要清除缓冲区。
关于c - '\n' 在 memset 之后保存在数组中 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58991504/