解析文本文件中的字符串,整数和浮点数

时间:2019-06-23 09:39:11

标签: c++ c++11

我有以下文本文件:

Jean Rousseau
1001 15.50
Steve Woolston
1002 1423.20
Michele Rousseau
1005 52.75
Pete McBride
1007 500.32
Florence Rousseau
1010 1323.33
Lisa Covi
1009 332.35
Don McBride
1003 12.32
Chris Carroll
1008 32.35
Yolanda Agredano
1004 356.00
Sally Sleeper
1006 32.36

我必须将字符串(Jean Rousseau),int s(1001)和float s(15.50)存储在3 std::vectors中。 / p>

我有一个可行的解决方案,但想知道这是否是正确的方法。

我的代码如下:

int counter=0;
std::string line;
std::ifstream myfile("InFile.txt");
std::vector<std::string> names;
std::vector<int> ids;
std::vector<float> balances;
int buf_int;
float buf_float;
while(myfile) {
   std::getline(myfile, line);
   std::cout << line << std::endl;
   std::stringstream ss(line);
   if(counter%2 == 0) {
        names.push_back(line);
   }
   else {
          if(ss >> buf_int) ids.push_back(buf_int);
          if(ss >> buf_float) balances.push_back(buf_float);
   }
   counter++;
}

请告诉我是否有更好的方法。谢谢。

1 个答案:

答案 0 :(得分:0)

正如πάνταῥεῖ所说。什么是更好的?由于征求意见,您的问题可能会结束。无论如何。我想使用算法给出一个替代答案。

我认为这3个数据“名称”,“ id”和“余额”属于同一数据。因此,我将它们放在一个结构中。 (是的,我无视您希望有3个单独的向量的方法。对不起。)

由于我们要读取此数据,因此将重载提取器运算符。以及插入程序运算符。也许以后可以添加一些其他功能。这样会更容易。

由于应该包含许多数据,因此std :: vector是存储该数据的理想解决方案。

在结构中具有3个项目,我们可以轻松地将所有项目一起读取,然后将它们放在向量中。

为了在main函数中读取整个文件,我们使用一个衬里。我们使用范围构造函数定义向量变量。

然后将包含所有数据的完整向量复制到std :: cout。

请注意。我没有错误处理。这需要添加。但这是一个简单的任务。此刻,一旦发现一些不匹配的文本,程序将停止读取。例如:最后一行必须有一个“ \ n”。

请参阅:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <iterator>

// Name Id and balance belong together. Therefore, we put it together in one struct
struct NameIdBalance    
{
    std::string name{}; int id{0};  float balance{0.0};
    // And since we want to read this data, we overload the extractor
    friend std::istream& operator>>(std::istream& is, NameIdBalance& nid) { 
        std::getline(is, nid.name); 
        is >> nid.id >> nid.balance;   is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        return is;  
    }
    // For debug purposes, we also overload the inserter
    friend std::ostream& operator << (std::ostream& os, const NameIdBalance& nid) { return os << "Name: " << nid.name << " (" << nid.id << ") --> " << nid.balance; }
};

int main()
{
    // 1. Open File
    std::ifstream myfile("r:\\InFile.txt");
    // 2 Read all data into a vector of NameIdBalance
    std::vector<NameIdBalance> nameIdBalance{ std::istream_iterator<NameIdBalance>(myfile), std::istream_iterator<NameIdBalance>() };

    // For debug purposes: Print complete vector to std::cout
    std::copy(nameIdBalance.begin(), nameIdBalance.end(), std::ostream_iterator<NameIdBalance>(std::cout, "\n"));
    return 0;
}

但是还有4200万种其他可能的解决方案。 。 。 _:-)

编辑:

在LightnessRacesinOrbit提示之后,我删除了POD一词。该结构不是POD。