我在构建程序时收到以下错误消息:
errorC2657:二进制'>>':找不到右侧的操作员 类型' const char [2]'(或没有可接受的转换)的操作数
以下是我的程序的源代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number1;
int number2;
int intSum;
int intdiff;
int intprod;
int intaver;
cout << "Enter the 1st and 2nd ODD integers (separate them by a space): ";
cin >> number1 >>" " >> number2;
intSum = abs(number1 + number2);
intdiff = abs(number1 - number2);
intprod = abs(number1 * number2);
intaver = abs((number1 + number2) / 2);
if ( number1%2 != 0)
cout << "You must enter ODD integers! See you next time." <<endl;
else if ( number2%2 != 0)
cout << "You must enter ODD integers! See you next time." <<endl;
else
{
cout << "The sum of the integers is"<<intSum<<endl;
cout << "The difference of the integers is"<<intdiff<<endl;
cout << "The product of the integers is"<<intprod<<endl;
cout << "The average of the integers is"<<intaver<<endl;
if (number1 > number2)
cout << "The first one "<< number1 <<" is bigger." <<endl;
else if (number2 > number1)
cout << "The second one "<< number2 <<" is bigger." <<endl;
else
cout <<"Both numbers are the same."<<endl;
}
return 0;
}
请帮我解决问题。我是初学者。
答案 0 :(得分:2)
本声明:
cin >> number1 >> " " >> number2;
尝试 写 您的输入到number1
,然后是字符串文字(const char[2]
),然后是number2
。这不是你想要的,特别是因为这些流足够聪明,可以自己跳过空白区域:
cin >> number1 >> number2;
您可以使用以下代码查看此内容:
#include <iostream>
int main() {
int i1, i2;
std::cout << "Please enter two integers: ";
std::cin >> i1 >> i2;
std::cout << "You entered " << i1 << " and " << i2 << '\n';
return 0;
}
,当运行时,它起作用:
Please enter two integers: 4 77
You entered 4 and 77
答案 1 :(得分:1)
cin >> number1 >>" " >> number2;
需要改为
cout << endl << "Enter first number : ";
cin >> number1;
cout << endl << "Enter second number : ";
cin >> number1;
>>
是为cin
定义为接收者的运算符,使用const char[2]
类型操作数是非法的。 paxDiablo解释说," "
是const char[2]
。但是,就像PaxDiablo说的那样,他的方式更好。
答案 2 :(得分:0)
这是问题所在:
cin >> number1 >>" " >> number2;
将其拆分为两个操作:
cin >> number1;
cin >> number2;
或
cin >> number1 >> number2;
operator>>
的{p> cin
读取到新行或空格。因此它将处理由空格分隔的输入。
答案 3 :(得分:0)
cin
无法接受字符串文字(" "
)。您需要将两个输入分开。
cin >> number1;
cin >> number2;
您还可以获取字符串并自行解析。
#include <string>
#include <boost/algorithm/string.hpp>
#include <vector>
std::string str;
cin >> str;
std::vector<std::string> strs;
boost::split(strs, "str", boost::is_any_of(" "));
int number1 = atoi(strs[0]);
int number2 = atoi(strs[1]);