簡體   English   中英

從文本文件中解析字符串、整數和浮點數

[英]Parsing strings, ints and floats from text file

我有以下文本文件:

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

我有一個可行的解決方案,但想知道這是否是正確的方法。

我的代碼如下:

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 個數據 'name'、'id' 和 'balance' 屬於一起。 因此,我會將它們放在一個結構中。 (是的,我忽略了您希望擁有 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM