首页 > 解决方案 > 调用 getline(std::istream&, int&) 没有匹配的函数

问题描述

我正在编写一个代码,该代码将任务语句作为用户的输入,并搜索其中是否存在“不”这个词,如果不存在,那么它会打印Real 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: 错误: 没有匹配函数调用'getline(std::istream&, int&)'</p>

标签: c++stringgetline

解决方案


std::getline有两个重载:

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

您正在尝试使用int参数调用它,但这是行不通的。

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

用于std::stoiint读后解析为std::string

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


推荐阅读