C++ 从包含字符的文件中读取数字

标签 c++ file input numbers ifstream

我希望能够将输入文件中的所有数字相加来求和,但我不确定如何真正做到这一点?我可以使用一些提示。 这是输入文本文件包含的内容:

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变量,但我不确定如何只读取文件中的数字。

最佳答案

这是一个 C 解决方案,似乎也同样有效:

#include <stdio.h>
#include <assert.h>
#define MAX_NAME_LENGTH 128
int main(int argc, char **argv)
{
    int number;
    char first_name[MAX_NAME_LENGTH];
    char second_name[MAX_NAME_LENGTH];
    FILE *fl=fopen("input.txt","rt");
    assert(fl && "could not open input file");

    while (fscanf(
        fl,
        "%s %s %d",
        first_name,
        second_name,
        &number) == 3)
    {
        printf("%s +++ %s +++ %d\n",first_name,second_name,number);
    }

    fclose(fl);
    return 0;
}

关于C++ 从包含字符的文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65839370/

相关文章:

forms - 基于输入的URL重定向,但如果输入的URL不存在,则发送回同一页面

python - C++算法的python包装器中的内存泄漏

php - jQuery $.ajax 和 php 删除文件

file - 某些行(虚线)使用 Groovy(Grails) 写入文件失败

C++ 在主函数中使用来自一个类的成员函数?

assembly - 缓冲输入如何工作

c++ - 根据循环内的两个不同条件更新计数器

c++ - 我应该使用 const 来使对象线程安全吗?

c++ - Visual Studio 2008 错误? "LNK1104 : cannot open file "

java - 如何让 Jlist 在添加新元素后自动向下滚动