Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 指数和平方根作为用户输入_C++_Input - Fatal编程技术网

C++ 指数和平方根作为用户输入

C++ 指数和平方根作为用户输入,c++,input,C++,Input,我如何允许用户在被询问时以e^x或sqrt(x)的形式输入数字,而不是仅以数字形式输入数字?谢谢。通常这是一个解析问题。就这两种形式而言,简单的解决方案可能是: string input; getline(cin, input); if (input[0] == 'e' && input[1] == '^') { int num = atoi(input.substr(2).c_str()); // probably better to use stringstreams

我如何允许用户在被询问时以e^x或sqrt(x)的形式输入数字,而不是仅以数字形式输入数字?谢谢。

通常这是一个解析问题。就这两种形式而言,简单的解决方案可能是:

string input;
getline(cin, input);
if (input[0] == 'e' && input[1] == '^') {
  int num = atoi(input.substr(2).c_str());  // probably better to use stringstreams here
  cout << exp(num) << endl;
} else if (input.substr(0, 5) == "sqrt(" && input[input.size() - 1] == ')') {
  int num = atoi(input.substr(5, input.size() - 6).c_str());
  cout << sqrt(num) << endl;
} else {
  cout << "error" << endl;
}
字符串输入;
getline(cin,输入);
如果(输入[0]=“e”&&input[1]=“^”){
int num=atoi(input.substr(2.c_str());//在这里使用stringstreams可能更好

您可能需要输入。您的语法可能非常简单,因此可以很容易地进行解析。将输入读取为字符串,检查格式是否有效,并根据其格式将字符串解释为值。输入是否始终是数字,形式是e^x,还是形式是sqrt(x),或者其他输入也可以吗?如果您可以向我们展示您现在尝试的不起作用的内容,我们可以提供帮助。如果您完全陷入困境,甚至不知道从哪里开始,那么请思考并进行一些实验,以找到一些有效的东西。严格来说,这两种东西都不是数字。用户输入字符序列,您必须对其进行解释。如果它们都是数字,您通常可以使用类似于
atoi(…)
的方法将数字作为10进制整数。除此之外的任何操作都将涉及解析输入和可能计算嵌套表达式。@templatetypedef用户主要输入十进制数字(例如0.1234567),但在某些情况下(为了方便起见),可以输入许多上述表单。谢谢,这是我所需要的。顺便说一句,您在else if条件的num定义中遗漏了.c_str()。