没有用于调用 getline(std::istream&, int&) 的匹配函数

No matching function for call to getline(std::istream&, int&)

我正在编写一个代码,该代码将任务语句作为用户的输入并搜索其中是否存在 "not" 这个词 如果不存在,那么它会打印 Real Fancy 否则它会打印 regularly fancy 但是我在这样一个简单的程序中遇到错误。

我的代码如下:

#include <iostream>
#include <string.h>
using namespace std;

int main () {
    string str2 (" not ");
    string str3 ("not ");
    string str4 ("not");

    int T;
    std::getline(std::cin, T);
    for (int k=0;k<T;k++){
        string str ;


        std::getline(std::cin, str);
        int len = str.size();
        //condition for only not as a sentence
        if ((str.find(str4) != string::npos) && len ==3) {
            cout<<"Real Fancy";
        }        
        // condition to check for not word in middle of a sentence eg. this is not good
        else if ((str.find(str2) != string::npos) ) {
            cout<<"Real Fancy";
        }        
        // condition if the statement ends with the word not 
        else if (str[len-1]=='t' && str[len-2]== 'o' && str[len-3]== 'n' && str[len-4]== ' '){
            cout<<"Real Fancy";
        }        
        // code to check for if statement starts with word not
        else if ((str.find(str3) != string::npos) ) {
            cout<<"Real Fancy";
        }
        else {
            cout<<"regularly fancy";
        }
        cout<<endl;
    }
    return 0;
}

我在 运行 这段代码中得到的错误是:

main.cpp:11:30: error: no matching function for call to ‘getline(std::istream&, int&)’

根据http://www.cplusplus.com/reference/string/string/getline/

您应该以这种形式使用 getline:

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

你这样做:

int T;
std::getline(std::cin, T);

T为整数,无法调用

std::getline 有两个重载:

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

您正在尝试使用 int 参数调用它,但该参数不起作用。

有两种方法可以解决这个问题:

读入std::string

后使用std::stoi解析int

使用 std::cin >> T 从流中直接读入 int。这不会特别考虑新行,而是使用任何空格作为整数之间的分隔符。因此,如果您尝试在每行中准确解析一个 int,则前一个选项更适合您。

std::getline() 函数不适用于整数类型。 如果要使用 std::getline() 作为整数,则应声明临时字符串类型值。 例如你的情况

int T;
std::string tmp_s;
std::getline(std::cin, tmp_s);
T = std::stoi(tmp_s);

std::getline 有以下重载:

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

而且,如您所见,其中 none 个接收整数作为第二个参数,因此这里有适合您的可能解决方案:

  • 如果您仅限于 C++11,请按以下方式使用 std::stoi
std::string line;
std::getline(std::cin, line);
int T = std::stoi(line);
  • 如果你能使用C++17,我强烈推荐你使用std::from_chars如下:
int value = 0;
std::string line;
std::getline(std::cin, line);
const auto result = std::from_chars(str.data(), str.data() + str.size(), value);
if (result.ec == std::errc()) {
    // strings is successfully parsed
}

为什么 std::from_charsstd::stoi 好?

因为 std::from_chars 是非抛出的并且可以为您提供更好的错误报告(这将为您提供有关转换结果的更多信息)。此外,根据某些资源,它比 std::stoi 快一点。阅读更多关于 std::from_chars here.