错误:与“operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>”}和“void”不匹配)| [重复]

问题描述 投票:0回答:1

这是我的代码。我已经检查了多次,进行了多次更改仍然是相同的错误。

#include <iostream>

using namespace std;

void checkAge(int age){
    if(age >= 18){
        cout<< "As your age is above 18, you are eligible to vote. \n";
    }
    else{
        cout<< "As your age is below 18, you aren't eligible to vote. \n";
    }
}
int main()
{
    int age;
        cout << "Enter your age. \n";
       cin >> age;
       cout << checkAge(age);


    return 0;
}
c++ c++11
1个回答
1
投票

您的函数

checkAge
不返回任何内容。所以只需从
 中删除 
cout

cout << checkAge(age);

即将上面的语句替换为:

checkAge(age);

解决方案2

另一种解决方案是从

int
返回
checkAge
。例如,您可以将函数定义更改为:

#include <iostream>

using namespace std;

void checkAge(int age){
    if(age >= 18){
        cout<< "As your age is above 18, you are eligible to vote. \n";
    }
    else{
        cout<< "As your age is below 18, you aren't eligible to vote. \n";
    }
    return age;//added return so that cout << checkAge(age) would work
}
int main()
{
    int age;
        cout << "Enter your age. \n";
       cin >> age;
       cout << checkAge(age);


    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.