我正在尝试使用 getline 逐行读取 csv 文件并将文件中的数据分开并将字符串转换为 int

发布于 2025-01-18 06:43:37 字数 1498 浏览 2 评论 0原文

我是初学者,我只需要一些帮助来了解为什么 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 不起作用一直说类似的话 没有重载函数的实例

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

我需要它来读取第一个数字,因为它是一个字符串,我不知道如何将其保存为 int

I am a beginner and I just need a bit of help on why I getline is showing an error:

this is what I have so far

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

I am able to get the file to open but I'm not sure why getline isn't working it keeps saying something like
no instance of overload function

My csv file looks like:
1,Laptop,799.99,1,cash,1100

I need it to read the first number and because Its a string i don't know how to save it as an int

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牛↙奶布丁 2025-01-25 06:43:37

多个错误。首先,您的程序中没有什么称为“ str”。我猜想它只是用作温度缓冲区的字符串

不执行此操作(!file.eof),它不会做您的想法。

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

接下来,此行不起作用,因为ID是ints和子字符串返回字符串。

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

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

    }

i 强烈建议您使用std :: vector而不是C风格的固定大小数组。需要5分钟来学习如何使用它们,并且它们有巨大的好处。如果您必须使用固定尺寸的数组,请使用std ::阵列而不是C风格

Multiple errors. First there is nothing called 'str' in your program. I will guess its just a string used as a temp buffer

do not do this (!File.eof) it doesnt do what you think.

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

Next this line doesnt work because ids are ints and substring returns a string.

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

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

    }

I strongly recommend you use std::vector instead of c-style fixed size arrays. Takes 5 minutes to learn how to use them and they have huge benefits. If you must use fixed size arrays use std::array instead of c-style

叫思念不要吵 2025-01-25 06:43:37

您可以读取字符串并尝试以不同的方式将其转换为数字。例如,从 C++17 开始,您可以使用 from_chars。它的重载之一:

  • 接收一对开始和结束 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.

You can read a string and try to convert it to a number in different ways. For example, since C++17, you can use from_chars. One of its overloads:

  • Receives a pair of begin and end char pointers, and an int variable,
  • tries to parse an int number, and
  • and returns the parsed number, together with a pointer to the first character that wasn't part of the match.
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 */ }

[Demo]

Full code (using a istrinstream instead of a 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文