簡體   English   中英

我正在嘗試使用 getline 逐行讀取 csv 文件並將文件中的數據分開並將字符串轉換為 int

[英]i am trying to use getline to read a csv file line by line and separate the data in the file and turn a string into int

我是初學者,我只需要一些幫助來了解為什么我的 getline 顯示錯誤:

這是我到目前為止所擁有的

#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>

using namespace std;

const double TAX_RATE = 0.0825;
const int MAX_ITEMS = 1000;
const int MAX_TRANSACTIONS = 100;

int main(int argc, char const *argv[]){
    string fname = "";
    int itemCnt = 0, start = 0, end = 0;
    int ids[MAX_ITEMS], qtys[MAX_ITEMS];
    double costs[MAX_ITEMS], subtotals[MAX_TRANSACTIONS],
           taxes[MAX_TRANSACTIONS], totals[MAX_TRANSACTIONS];
    string names[MAX_ITEMS], paymentTypes[MAX_ITEMS], payments[MAX_ITEMS];
     ifstream iFile;

     if ( argc != 2 ) { 
        cout<<"usage: "<< argv[0]<< " <file name>" <<endl;
        return 0;
    } else  { 
        iFile.open(argv[1]);
    }
        if (!iFile) { 
           cout<<"Error: Invalid file name"<<endl;
           cin.clear();
        }             

        while (!iFile.eof())
    {
        getline(iFile,str); //this isn't working 

        int commaLoc = str.find(',');
        ids[itemCnt]= str.substr(0,commaLoc);
        str = str.substr(commaLoc +1, str.length());
        //string to int I'm not sure how to do I know its something with stoi() but not sure how to format it 

        }

        return 0;
}

我能夠打開文件,但我不確定為什么 getline 不工作它一直在說沒有過載實例 function

我的 csv 文件如下所示:1,Laptop,799.99,1,cash,1100

我需要它來讀取第一個數字,因為它是一個字符串,我不知道如何將它保存為一個 int

多個錯誤。 首先,您的程序中沒有名為“str”的內容。 我猜它只是一個用作臨時緩沖區的字符串

不要這樣做(.File.eof)它不會按照您的想法進行。

    while (iFile)
     {
         string str; <<<<<==== added
         getline(iFile,str); //this isn't working <<<===is now
         int commaLoc = str.find(',');

接下來這一行不起作用,因為 id 是整數並且 substring 返回一個字符串。

         //   ids[itemCnt]= str.substr(0,commaLoc);

          ids[itemCnt]= stoi(str.substr(0,commaLoc)); <<<<==== fixed
          str = str.substr(commaLoc +1, str.length());

    }

強烈建議你使用std::vector而不是 c 風格的固定大小 arrays。花 5 分鍾來學習如何使用它們,它們有很大的好處。 如果必須使用固定大小 arrays,請使用 std::array 而不是 c-style

您可以讀取字符串並嘗試以不同的方式將其轉換為數字。 例如,由於 C++17,您可以使用from_chars 它的重載之一:

  • 接收一對 begin 和 end char 指針,以及一個 int 變量,
  • 嘗試解析一個 int 數字,並且
  • 並返回解析后的數字,以及指向不屬於匹配項的第一個字符的指針。
int i{};
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), i);
if (ec == std::errc{}) { /* do something with i */} else { /* error */ }

[演示]

完整代碼(使用istrinstream而不是ifstream ):

#include <charconv>  // from_chars
#include <iomanip>
#include <iostream>
#include <sstream>  // istringstream
#include <system_error>  // errc

constinit const int MAX_ITEMS = 10;

int main() {
    std::istringstream iss{
        "1,Laptop,799.99,1,cash,1100\n"
        "2,PC,688.88,2,card,1101\n"
        "blah,Keyboard,39.00,3,cash,1102"
    };

    size_t itemCnt{};
    int ids[MAX_ITEMS]{};
    std::string str{};
    while (std::getline(iss, str)) {
        // Parse counter
        int i{};
        auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), i);
        if (ec == std::errc{}) {
            ids[itemCnt] = i;

            // Remaining string
            std::string remaining_string{ str.substr(ptr - str.data() + 1) };
            std::cout << ids[itemCnt] << ", " << remaining_string << "\n";
        }
        else {
            std::cout << "Error: invalid counter.\n";
        }

        ++itemCnt;
    }
}

// Outputs:
//
//   1, Laptop,799.99,1,cash,1100
//   2, PC,688.88,2,card,1101
//   Error: invalid counter.

暫無
暫無

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

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