【问题标题】:no instance of "getline" matches the argument list没有“getline”实例与参数列表匹配
【发布时间】:2021-06-22 12:50:56
【问题描述】:

我正在使用 GeeksForGeeks ReadCSV 函数读取 CSV 文件,我完全按原样复制了代码,但出现此错误:“没有“getline”实例与参数列表匹配”谁能告诉我为什么会这样?

这是完整的代码:

void ReadCSV(std::string filename, std::vector<RowVector*>& data)
{
    data.clear();
    std::ifstream file(filename);
    std::string line, word;
    // determine number of columns in file
    getline(file, line, '\n');
    std::stringstream ss(line);
    std::vector<Scalar> parsed_vec;
    while (getline(ss, word, ', ')) {
        parsed_vec.push_back(Scalar(std::stof(&word[0])));
    }
    uint cols = parsed_vec.size();
    data.push_back(new RowVector(cols));
    for (uint i = 0; i < cols; i++) {
        data.back()->coeffRef(1, i) = parsed_vec[i];
    }

    // read the file
    if (file.is_open()) {
        while (getline(file, line, '\n')) {
            std::stringstream ss(line);
            data.push_back(new RowVector(1, cols));
            uint i = 0;
            while (getline(ss, word, ', ')) {
                data.back()->coeffRef(i) = Scalar(std::stof(&word[0]));
                i++;
            }
        }
    }
}

【问题讨论】:

  • 错字:', ' 应该是 ','
  • 请注意,geeksforgeeks 是一个臭名昭著的网站。
  • 实际上我很惊讶代码中的错误如此之少。虽然一般来说,从某个地方复制一些代码并期望它做正确的事情并不总能奏效。
  • 我很绝望,是的,我修复了他们代码中的其他错误......
  • 多字符字面量 ', ' 的类型为 int,而 char 应该在此处。

标签: c++ fstream getline


【解决方案1】:

getline 的第三个参数是单个字符(见下文)。当您传递 ', ' 时,您正试图在单引号中传递两个字符。

https://www.cplusplus.com/reference/string/string/getline/

istream& getline (istream& is, string& str, char delim);

将分隔符更改为 ','(单个字符),应该没问题。

如果您对单引号和双引号感兴趣,以及将多个字符放在单引号中会发生什么,下面的帖子有一些很好的讨论。 (Single quotes vs. double quotes in C or C++)

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 2023-03-10
    • 1970-01-01
    • 2014-12-27
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多