gpt4 book ai didi

c++ - 我想创建一个函数来读取输入的每一行并生成其总和并使用 C++ 将其保存为 sum.txt

转载 作者:太空宇宙 更新时间:2023-11-03 10:44:36 25 4
gpt4 key购买 nike

假设我有以下输入:

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");

并不确定下一步该做什么。

我的一些 friend 推荐我使用 getline,将每一行标记化,然后将字符串转换为整数,但我想知道是否有更简单的方法无需来回更改类型(int 到 string,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

关于c++ - 我想创建一个函数来读取输入的每一行并生成其总和并使用 C++ 将其保存为 sum.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com