首页 > 解决方案 > 文本文件中的整数

问题描述

所以我需要编写一个程序来生成文本文件中所有空格分隔的整数的总和。到目前为止我的代码看起来像这样

#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++file

解决方案


您需要检查读入的字符是否为数字,因为在 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;
}

推荐阅读