只是有一个简短的问题.我已经在互联网上看了很多,我找到了一些解决方案,但没有一个已经有效.看一下将字符串转换为int,我不是指ASCII码.
为了快速减少,我们将方程作为字符串传递.我们要将其分解,正确格式化并求解线性方程.现在,在说,我无法将字符串转换为int.
我知道字符串将采用格式(-5)或(25)等,所以它肯定是一个int.但是我们如何从字符串中提取它?
我想的一种方法是通过字符串运行for/while循环,检查一个数字,然后提取所有数字,然后查看是否有一个前导' - ',如果存在,则将int乘以 - 1.
虽然这个小问题看起来有点过于复杂.有任何想法吗?
我试图使用stoiC++ 11中的函数将字符串元素转换为整数并将其用作pow函数的参数,如下所示:
#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
string s = "1 2 3 4 5";
//Print the number's square
for(int i = 0; i < s.length(); i += 2)
{
cout << pow(stoi(s[i])) << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了这样的错误:
error: no matching function for call to
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;
Run Code Online (Sandbox Code Playgroud)
有人知道我的代码有什么问题吗?
可能重复:
c ++将字符串转换为int
我有用户输入9个数字.我需要将字符串数转换为int
string num;
int num_int, product[10];
cout << "enter numbers";
cin >> num;
for(int i =0; i<10; i++){
product[i] = num[i] * 5; //I need the int value of num*5
}
Run Code Online (Sandbox Code Playgroud)