首页 > 解决方案 > 如何将 getline 与标准输入一起使用?

问题描述

std::stringstream line;
getline(stdin, line);

有人可以向我解释为什么我在尝试编译时收到“没有匹配的函数调用 getline”错误吗?

标签: c++

解决方案


C++ 没有getlineFILE*( stdin) 和iostream( line) 作为参数。

相反,你应该

std::string line; 
if (std::getline(std::cin, line)) // ensure read succeeded
{
    std::stringstream linestream(line);
    // opperate on linestream    
}

与.std::cin关联的 C++ IO 流在哪里?stdin

如果您绝对必须stdin在原始版本中使用,在符合 POSIX 的系统上,您可以

char * line; 
size_t len; 
if (getline(&line, &len, stdin) != -1) // ensure read succeeded
{
    std::stringstream linestream(line);
    free(line); // release the buffer allocated by getline
                // must free(line). Do not delete line;
    // opperate on linestream    
}

您已将其标记为 C++,因此我推荐前者。

C++ 文档std::getline

POSIX 文档getline


推荐阅读