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

Parsing strings, ints and floats from text file

本文关键字:整数 浮点数 字符串 文本 文件      更新时间:2023-10-16

我有以下文本文件:

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

我必须将字符串(让·卢梭)、ints(1001)和floats(15.50)存储在 3 个std::vectors中。

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

我的代码如下:

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++;
}

如果有更好的方法,请告诉我。谢谢。

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

在我看来,3个数据"名称","id"和"余额"是在一起的。因此,我会将它们放在结构中。(是的,我忽略了您拥有 3 个独立向量的愿望。我道歉。

由于我们要读取此数据,因此我们将重载提取器运算符。还有机械臂操作员。也许以后可以添加一些附加功能。这样就容易多了。

而且因为应该有很多这样的数据,所以 std::vector 是存储这些数据的理想解决方案。

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

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

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

请注意。我没有进行错误处理。这需要添加。但这是一项简单的任务。目前,一旦找到一些不匹配的文本,程序就会停止读取。例如:最后一行必须有一个""。

请看:

#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。