c - 如何从这种输入格式中提取数字?
问题描述
我需要像我突出显示的行一样“扫描”。我如何提取数字?我在课程的开始,所以不要发布我可能还没有研究过的过于复杂的解决方案。
输入(房屋成本、首付、储蓄、储蓄年率、抵押年率、工资、部分储蓄、年薪、房租):
(600000, 0.15, 50000, 0.02, 0.03, 10000, 0.3, 0.03, 2000)
C 语言。
解决方案
我如何提取数字?
简单的方法是读取该行,fgets()
然后解析sscanf()
并"%n"
记录扫描的偏移量,如果它到达那么远。
使用允许(,)
分隔符附近有空格的格式。
"%lf"
已经消耗了领先的空白。
#define EXPECTED_SIZE 100
char buffer[EXPECTED_SIZE * 2]; // Be generous in buffer size
// Was a line successfully read?
if (fgets(buffer, sizeof buffer, stdin)) {
// Example code simplified to 3 variables
double House_cost, down_payment, savings;
int n = 0;
sscanf(buffer, " (%lf ,%lf ,%lf ) %n",
&House_cost, &down_payment, &savings, &n);
// Did scanning reach the %n and was that the end of the line?
if (n > 0 && buffer[n] == '\0') {
Success();
} else {
Failed();
}
}
一个好的解析器已经准备好检测错误的输入。不要假设输入格式正确。
推荐阅读
- asp.net-mvc - 如何在 Ajax 发布后更新 Partial 视图
- sharepoint - 如何修改 Office365 Onenote 网页视图以隐藏导航面板
- android - ListView onClick 没有显示适配器到 CardView 详细信息
- ios - 尝试使用在 SafariViewController 中启动链接的 tableviewcells 快速创建选项卡式应用程序
- c# - asp.net mvc + angularJs中的模块注册问题
- css - 有没有办法让这个下拉菜单看起来像一个表格?
- c# - 枚举类型不再在 .Net core 3.0 FromBody 请求对象中工作
- java - 读取带有波兰语字母的 ANSI 文件并在没有口音的控制台中显示
- android - adb“连接的设备列表”为空,用于远程 Debian 虚拟机上的 USB 连接
- asp.net - 在填充到 gridview 时修改 Eval("data")