gpt4 book ai didi

c++ - 减去 std::strings 时出现编译器错误

转载 作者:行者123 更新时间:2023-11-27 23:03:23 26 4
gpt4 key购买 nike

我是 C++ 的初学者,所以我只是在阅读文章和书籍时弄乱了一些东西。但是我花了 20 分钟一遍又一遍地重新阅读这篇文章,但我不知道它有什么问题。

#include <iostream>
#include <string>

using namespace std;

int main ()
{

cout << "Hello there, this is your personal simple calculator.";
cin.get();
cout << "Type in what you want to do. (Addition, Subtraction, Multiplication, Division)"<< endl;
string c;
getline (cin, c);

if (c == "Addition")
{
string a_1;
string a_2;
cout << "You chose addition. Press enter" << endl ;
cin.get();
cout << "Type in the first value: ";
getline( cin, a_1);
cout << "Type in the second value: ";
getline (cin, a_2);
cout << a_1 << " + " << a_2 << " = " << a_1 + a_2 << endl;
}
else
{
cout << "You spelled it wrong.";
return 0;
}
if ( c == "Subtraction")
{
string s_1;
string s_2;
cout << "You chose subtraction. Press enter" << endl ;
cin.get();
cout << "Type in the first value: ";
getline (cin, s_1);
cout << "Type in the second value: ";
getline (cin, s_2);
cout << s_1 << " - " << s_2 << " = " << s_1 - s_2 << endl;
}

}

我认为这是唯一的错误

42 83 C:\Users\Jason\Desktop\Lesson - Header Files\LH1.cpp [Error] no match for 'operator-' in 'first_argument - second_argument'

我不明白。加法符号有效,除减法外的所有符号都有效。所以我搞砸了其他事情

cout << first_argument << " - " << second_argument << " = " << first_argument - second_argument << endl;

但是减法部分工作正常。我不明白。请帮忙

最佳答案

string 可以处理文本。当您添加两个字符串时,它们会连接起来("2"+"2"=="22",而不是 "4")。字符串没有operator-

要处理 float ,请使用double。要处理整数,请使用 int:

double d1, d2;
//some output
cin >> d1;
//some output
cin >> d2;
cout << d1 << " - " << d2 << " = " << (d1-d2) << '\n';

关于c++ - 减去 std::strings 时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25558925/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com