c - '\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
解决方案
您在代码中有多个问题。他们之中有一些是
scanf("%s", &c);
是错的。c
是 achar
,您必须为此使用%c
转换说明符。您从未检查调用的返回值
scanf()
以确保成功。在扫描字符输入时,您没有清除任何现有输入的缓冲区。任何现有字符,包括缓冲区中已经存在的换行符 (
'\n'
) 都将被视为 的有效输入%c
。您需要在读取字符输入之前清除缓冲区。
推荐阅读
- java - 使用 selenium 检查表中的复选框,直到表的最后一个索引页
- java - firebase 中的数据更改发生在第二次单击按钮时,第一次单击什么也不做
- node.js - mongo $pull 不删除字符串
- java - 数组在显示结果时是否跳过空位置?
- random - 分层随机抽样 Excel
- c++ - BFS(广度优先搜索)邻接矩阵 C++
- reactjs - React 单元测试传单
- botframework - 将 qnamaker 与 V3 MS bot 一起使用的最佳方式
- php - Html:linkroute 和 Laravel 中编辑功能的简单链接之间的区别
- html - bootstrap 4中的全宽div