【问题标题】:Why do std::istringstream only work here with a constructor? [duplicate]为什么 std::istringstream 只能在这里使用构造函数? [复制]
【发布时间】:2021-09-08 22:39:04
【问题描述】:

下面的代码按预期编译和工作。在第 11 行,当我更改时
std::istringstream iss(temp)

std::istringstream iss()
,它停止工作。第18行出现错误,iss.str(temp):
expression must have class type but it has type "std::istringstream (*)()"

为什么对构造函数进行更改会产生影响?我检查了docs,它不应该有所作为,但我一定遗漏了一些东西。有什么想法吗?

#include <vector>
#include <iostream>
#include <string>
#include <sstream>

int main() {

    int n, m;
    std::string temp;
    std::vector<int> ranked, player;
    std::istringstream iss();

    // Get the Input

    std::getline(std::cin, temp);
    n = std::stoi(temp);
    std::getline(std::cin, temp);
    iss.str(temp);
    while(!iss.eof()) {
        std::getline(iss, temp, ' ');
        ranked.push_back(std::stoi(temp));
    }

    return 0;
}

【问题讨论】:

  • 查找“Most Vexing Parse” - 如果表达式可以被解释为函数声明,那么它被这样解释。跨度>

标签: c++ istringstream


【解决方案1】:

std::istringstream iss()是函数的声明,名称为iss,返回值为std::istringstream

【讨论】:

    【解决方案2】:
    std::istringstream iss();
    

    是函数iss 的声明。删除 () 以声明对象。

    另请注意,您使用的while(!iss.eof())wrong。循环应该是:

    while(std::getline(iss, temp, ' ')) {
        ranked.push_back(std::stoi(temp));
    }
    

    【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多