大家好,我正在尝试 Bjarne Stroustrup 的 PPP 书中的练习。我已经设法完成了大部分练习,但是我遇到了一个问题。
在这个程序中,基本思想是有一个可以接受整数和字符串输入的计算器。实际的计算器部分工作正常,我可以毫无问题地输入整数。我的问题在于尝试将字符串输入说“一”转换为整数一。
我如何做到这一点的想法是在我的向量中运行一个 for 循环,该向量以单词的形式存储数字 1-10,当它找到一个包含与用户输入匹配的字符串的索引时,它使用 for 循环计数器变量;这应该等于用户输入的数量。
这个想法应该可行,并且 Bjarne 的示例代码使用了类似的想法,但是我的略有不同并且似乎不起作用,我遇到的问题似乎是当将用户输入与向量索引进行比较时它没有似乎找不到任何匹配项,我已经搞砸了几个小时,似乎找不到原因。无论如何这里是代码:
//simple calculator program, users can input words 1-10 and an integer will be returned.
// header files
#include "../../std_lib_facilities.h"
//global varible- vector set up here.
vector<string> numbers;
//functions, one to initiliase vectors, one to get number, and a main function.
void initiliase() {
numbers.push_back ("zero");
numbers.push_back ("one");
numbers.push_back ("two");
numbers.push_back ("three");
numbers.push_back ("four");
numbers.push_back ("five");
numbers.push_back ("six");
numbers.push_back ("seven");
numbers.push_back ("eight");
numbers.push_back ("nine");
numbers.push_back ("ten");
}
int get_number(){
char choice;
string type_val;
int val = 0;
cout << "do you wish to enter a number or word? n/w" << endl;
cin >> choice;
if ( choice == 'n'){
cin >> val;
return val;
}
else if(choice == 'w'){
cin >> type_val;
for (int i = 0; i<numbers.size(); i++){
if (numbers[i] == type_val)
val = i;
else
cout << "number not found in vector.";
return val;
}
}
}
void print_answer(int ans, char oper, int val1,int val2) {
cout << "Your Answer is:" << ' ' << val1 << ' ' << oper << ' ' << val2 << ' ' << '=' << ans << endl;
}
void main() {
initiliase();
int val1, val2, answer;
char op;
val1 = get_number();
val2 = get_number();
cout << "Please input operation:";
cin >> op;
switch (op){
case '+': cout << "You have chosen addition!" << endl;
answer = val1 + val2;
print_answer (answer, op, val1, val2);
break;
case '-': cout << "you have chosen subtraction!" << endl;
answer = val1 - val2;
print_answer (answer, op, val1, val2);
break;
case '*': cout << "you have chosen multiplication!" << endl;
answer = val1 * val2;
print_answer (answer, op, val1, val2);
break;
case '/': cout << "you have chosen division!" << endl;
answer = val1 / val2;
print_answer (answer, op, val1, val2);
break;
case '%': cout << "you have chosen modulos!" << endl;
answer = val1 % val2;
print_answer (answer, op, val1, val2);
break;
default: cout << "incorrent operation" << endl;
}
keep_window_open ("~");
}