我是编程新手,正在学习C ++课程。这是我的任务:
Write a program that continually takes in input until the user types “done”.
When the input received is a “+”, start adding together the values of each
subsequent input into a variable. When the input is a “-”, start subtracting
the values of the subsequent input from that same variable. Do nothing with
inputs that are received before either a “+” or “-” operation. Output the
final result to the screen.
这是我到目前为止所做的:
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
int main()
{
string input;
int number;
vector<int> numbers;
cout << "Type some stuff: \n";
for (;cin >> input && input != "done";)
{
if (input == "done")
break;
else if (input == "+")
cout << input;
}
return 0;
}
这是输出:
Type some stuff:
Hello world done
HelloworldProgram ended with exit code: 0
我无法弄清楚下一部分。谢谢你的帮助。
答案 0 :(得分:1)
从赋值中可以假设输入是由空格分隔的单词/数字。我认为作为赋值的一部分给出的代码行for (;cin >> input && input != "done";)
支持这种假设。然后,以下输入应该实现以下输出:
100 200 + 100 200 - 10 done --> 290
以下是实现此目的的代码:
int main()
{
string input;
int result;
int mode = 0;
cout << "Type some stuff: \n";
for (;cin >> input && input != "done";)
{
if (input == "done")
break;
else if (input == "+")
mode = 1;
else if (input == "-")
mode = -1;
else {
try {
int number = stoi(input);
number *= mode;
result += number;
}
catch( const std::exception& e ) { } // ignore any conversion errors
}
}
cout << result;
return 0;
}