首页 > 解决方案 > 一个错误,我试图创建一个函数来处理一个人的症状,然后将它存储在一个向量字符串中作为“Y”或“N”,我得到了这个

问题描述

#include <iostream>
#include <vector>

using namespace std;

string disease(vector<string> symptom, vector<string> name, int patientnum){
    string holder;
    cout << "is " << name[patientnum] << " experiencing  " << symptom[patientnum] << " Y/N";
    cin  >> holder;
    if(holder == "Y" || holder == "y"){
        return symptom.push_back("Y");
    }
    else if(holder == "N" || holder == "n"){
        return symptom.push_back("N");
    }
    else{
        cout <<"Please input Y/N" << endl;
        cout <<"Program exiting...";
    }
}

int main()
{
    vector<string> dry, sneeze, namex;
    int patientn = 0;
    string input;
    while(patientn < 2){
        cout << "Name: ";
        cin  >> input;
        namex.push_back(input);
        disease(dry[patientn], namex[patientn], patientn);
        patientn++;
    }
    
    for(patientn=0; patientn<namex.size(); patientn++){
        cout << namex[patientn] << " is experiencing dry cough = " << dry[patientn] << endl;
        cout << namex[patientn] << " is experiencing sneezing = " << sneeze[patientn] << endl;
    }
    return 0;
}

这是我得到的错误

error: could not convert ‘symptom.std::vector<_Tp, _Alloc>::push_back, std::allocator > >(std::basic_string(((const char*)"Y"), std::allocator()))’ from ‘void’ to ‘std::string {aka std::basic_string}’

我是 IT 专业的新生,如果我制作这个程序的逻辑很愚蠢,而且我的变量命名令人困惑,我很抱歉。

因此,在 while 循环中,我要求输入一个名称,然后将其存储在名称向量中,然后我调用该函数来要求输入。"

cout <<"Is " << name << " experiecing " << symptom; //something like this but i also use an int patientnum to get the name[patientnum]

然后得到 y/n 作为答案。然后我做一个 if 接受大写或小写的答案并返回症状.push_back "Y" 或 "N"

底部的for循环是打印名称然后是Y/N

或者你们能建议我一个更好的方法吗,我愿意学习任何东西。

标签: c++vector

解决方案


将函数更改为 void,因为您不想从中返回任何内容。

void disease(vector<string> symptom, vector<string> name, int patientnum){
    string holder;
    cout << "is " << name[patientnum] << " experiencing  " << symptom[patientnum] << " Y/N";
    cin  >> holder;
    if(holder == "Y" || holder == "y"){
        symptom.push_back("Y");
    }
    else if(holder == "N" || holder == "n"){
        symptom.push_back("N");
    }
    else{
        cout <<"Please input Y/N" << endl;
        cout <<"Program exiting...";
    }
}

不幸的是,这只是您的代码的众多问题之一。

顺便说一句,如果您花一些时间为您的函数和变量选择合乎逻辑且有意义的名称,您会发现编程更容易。好笑。编程战斗的一半是清楚地思考你在做什么,而毫无意义或随意的名字表明你没有清楚地思考。


推荐阅读