繁体   English   中英

我想创建一个函数,该函数读取输入的每一行并产生其总和,并使用C ++将其另存为sum.txt

[英]I would like to create a function that reads each line of the input and produces its sum and save that as sum.txt using C++

假设我有以下输入:

1 2 3 
5 6
10 11
13

存储在wow.txt

我想创建一个函数,该函数读取输入的每一行并产生其总和,并使用C ++将其另存为sum.txt

在输入文件中,我们具有以下内容:

1)我们不知道每行的长度,但是最多有10个整数。
2)每个整数都用空格分隔。

所以我开始

ifstream inFile;
inFile.open("wow.txt");
ofstream outFile;
outFile.open("sum.txt");

而且不确定下一步该怎么做。

我的一些朋友推荐我使用getline,将每行标记化,然后将字符串转换为整数,但是我想知道是否有更简单的方法来实现,而不必来回更改类型(将int更改为string,将字符串更改为int) 。

任何帮助将不胜感激。

使用getlineistringstream

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

int main() {
  ifstream inFile("wow.txt");
  if (!inFile) {
    cerr << "File wow.txt not found." << endl;
    return -1;
  }
  ofstream outFile("sum.txt");

  // Using getline() to read one line at a time.
  string line;
  while (getline(inFile, line)) {
    if (line.empty()) continue;

    // Using istringstream to read the line into integers.
    istringstream iss(line);
    int sum = 0, next = 0;
    while (iss >> next) sum += next;
    outFile << sum << endl;
  }

  inFile.close();
  outFile.close();
  return 0;
}

输出:

6
11
21
13

我不是std::getline() std::istringstream ,然后使用std::istringstream方法:流不是免费创建的。 至少内部的std :: istringstream应该构造一次,然后重置,即使这需要清除标志:

std::istringstream iss;
for (std::string line; std::getline(std::cin, line); ) {
    iss.clear();
    iss.str(line);
    // ...
}

调用iss.clear()重置流的错误标志,这些错误标志将被设置为最终指示没有更多数据。 使用iss.str(line)设置字符串流的内部数据。

代替创建或设置std::istringstream我将安排换行符将输入流设置为false,即设置std::ios_base::failbit 对于高级方法,我将更改流使用的std::locale std:ctype<char>方面的空白定义。 但是,那是大枪! 对于手头的任务,可以在每个输入之前使用一个简单的操纵器来达到类似的效果:

#include <iostream>
#include <cctype>

using namespace std;

std::istream& skipspace(std::istream& in) {
    while (std::isspace(in.peek())) {
        int c(in.peek());
        in.ignore();
        if (c == '\n') {
            in.setstate(std::ios_base::failbit);
            break;
        }
    }
    return in;
}

int main() {
    int sum(0);
    while (std::cin >> sum) {
        for (int value; std::cin >> skipspace >> value; ) {
            sum += value;
        }
        std::cout << "sum: " << sum << "\n";
        std::cin.clear();
    }
    return 0;
}

大多数魔术都在操纵器 skipspace() :它跳过空格,直到到达流的末尾或使用了换行符为止。 如果使用了换行符,则通过设置标志std::ios_base::failbit将流置于失败状态。

计算总和的循环仅读取第一个值。 如果此操作失败(例如,因为找到了非整数),则输入失败,并且不再生成任何输出。 否则,使用skipspace()跳过空白,然后读取下一个值。 如果其中任何一个失败,则打印当前sum ,并清除流以读取下一个总和。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM