c++ - 文本文件中的整数
问题描述
所以我需要编写一个程序来生成文本文件中所有空格分隔的整数的总和。到目前为止我的代码看起来像这样
#include "std_lib_facilities.h"
int main()
{
int sum = 0;
char text;
ifstream txtfile;
txtfile.open("intfile.txt");
if (!txtfile) {
cout << "Unable to open file";
exit(1);
}
while (txtfile >> text ){
if (txtfile){
sum = sum + text;
}else if (txtfile.fail()){
txtfile.clear();
for (char text;txtfile>>text && !isdigit(text);)
{};
}
}
txtfile.close();
cout << "Sum = " << sum << endl;
return 0;
}
我的文本文件如下所示:
bears: 17 elephants 9 end
我的问题是为什么我的输出是 Sum = 2019。而且我没有任何错误,所以我不知道出了什么问题。
解决方案
您需要检查读入的字符是否为数字,因为在 c++ 中,如果您对其进行数字操作,char 类型会隐式转换为其 ASCII 值。由于数字的 ASCII 值与实际值之间的差异,您需要减去表中的第一个数字“0”。
#include <iostream>
#include <fstream>
#include <cctype>
int main()
{
int sum = 0;
char text;
std::ifstream txtfile;
txtfile.open("../intfile.txt");
if (!txtfile.is_open()) {
std::cout << "Unable to open file" << std::endl;
exit(1);
}
while (txtfile >> text ){
if (txtfile && isdigit(text)){ // check if character is a digit
sum += text - '0'; // take into account the ASCII table offset
}else if (txtfile.fail()){
txtfile.clear();
for (char text;txtfile>>text && !isdigit(text);)
{};
}
}
txtfile.close();
std::cout << "Sum = " << sum << std::endl;
return 0;
}
推荐阅读
- babylonjs - 使用 parcel.js 摇树 BabaylonJs
- javascript - 使用 redux 更新 React ApexCharts
- docker - web-api 无法连接到 Docker 作曲家网络中的 sqlserver
- amazon-web-services - 如何运行 AWS Cron 作业,它将运行一整周,但有一个例外(我不应该在上午 9 点到上午 9 点的周六运行)
- google-bigquery - Apache Beam - Bigquery 流式插入显示 RuntimeException:ManagedChannel 分配站点
- c# - 有没有办法将 Authorize 属性与没有身份验证标头的请求一起使用?
- android - Firebase 分析显示每日活跃用户异常
- c# - PHP SQL 从用户名获取日期时间并与今天的日期进行比较
- logstash - 消息的 Logstash grok 模式
- html - 带有复选框预选选项的垫树在页面加载时无法在级别 1 中工作