【发布时间】:2021-04-26 13:53:15
【问题描述】:
我希望能够将输入文件中的所有数字相加以求总和,但我不确定如何真正做到这一点?我可以使用一些指针。 这是输入文本文件包含的内容:
Mark Cyprus 21
Elizabeth Monroe 45
Tom McLaugh 82
Laura Fairs 3
Paul Dantas 102
这是我目前的代码
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
using namespace std;
class Age
{
//Create the variables
string first_name, last_name;
int age, sum_age, average_age;
public:
bool isblank(const std::string& s)
{ //True if s is empty or only contains space and/or TABs.
return s.find_first_not_of(" \t")==std::string::npos;
}
void readFile ()
{
ifstream file;
file.open("input_age.txt");
string line;
// file opened?
if (! file) {
cerr << "can’t open input file." << endl;
exit(EXIT_FAILURE);
}
// getline is true for as long as end of file is not reached
while(std::getline (file,line)){
if (! isblank(line)){
// now the variable string "line" contains the line content
file >> first_name;
file >> last_name;
file >> age;
}
}
file.close();
}
有没有办法只捕捉年龄而不是阅读名字?我不相信我真的需要这个名字。所以最好删除那些 first_name 和 last_name 变量,但我不确定如何只读取文件中的数字。
【问题讨论】:
-
当你的格式已知时,使用
fscanf...这是最简单的方法 -
谢谢,我知道如何将年龄相加并求和。有没有办法创建一个打印出每个年龄的方法?当我尝试时,它只打印出最后一个年龄 102。 fscanf 对此有帮助吗?
标签: c++ file input numbers ifstream