C++ 将字符串元素转换为整数(C+;+;11)
我尝试使用C++11中的C++ 将字符串元素转换为整数(C+;+;11),c++,string,c++11,type-conversion,integer,C++,String,C++11,Type Conversion,Integer,我尝试使用C++11中的stoi函数将字符串元素转换为整数,并将其用作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 f
stoi
函数将字符串元素转换为整数,并将其用作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;
}
}
error: no matching function for call to
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串s=“1 2 3 4 5”;
//打印数字的平方
对于(int i=0;istd::string
,coutstoi()
可以正常工作。
所以
因为,这里传递的是一个char
,所以可以使用以下代码行来代替for循环中使用的代码行:
std::cout << std::pow(s[i]-'0', 2) << "\n";
std::cout问题是stoi()
不能与char
一起使用。或者,您可以使用std::istringstream
来执行此操作。另外std::pow()
接受两个参数,第一个是基,第二个是指数。您的注释表示数字的平方,因此
#include <sstream>
string s = "1 2 3 4 5 9 10 121";
//Print the number's square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
cout << pow(stoi(num), 2) << endl;
}
#包括
字符串s=“1 2 3 4 5 9 10 121”;
//打印数字的平方
istringstream iss(s);
字符串数;
while(iss>>num)//由s中的空格标记
{
cout类似于:
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string s = "1 2 3 4 5";
istringstream iss(s);
while (iss)
{
string t;
iss >> t;
if (!t.empty())
{
cout << pow(stoi(t), 2) << endl;
}
}
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串s=“1 2 3 4 5”;
istringstream iss(s);
while(国际空间站)
{
字符串t;
iss>>t;
如果(!t.empty())
{
问题是s[i]
显然是一个char
。一个字符。现在看看stoi
()的参数必须是什么,你应该能够自己计算出来。stoi
与std::string
(和std::wstring
)一起工作,但是s[i]
是一个char
。如果我使用substr
函数,它会工作吗?因为从我读到的,它返回字符串类型?@AkhmadZaki是的,substr
会工作。如果s包含一个大于9的数字怎么办?是的,我忘了包含指数。谢谢你的回答。上面的代码对于数字大于1的整数仍然有效吗?@AkhmadZak是的,最好使用std::istringstream
而不是std::stringstream
,这样编译器就可以检测到意外的,谢谢你的回答。只要字符串中的每个字符都在'0'
到'9'
的范围内,这个技巧就可以保证有效。字符串中只有一个空格,你就有可能失去它定义的行为。它也更难阅读。这一个应该被工程上的答案所接受。谢谢你的答案。
#include <sstream>
string s = "1 2 3 4 5 9 10 121";
//Print the number's square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
cout << pow(stoi(num), 2) << endl;
}
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string s = "1 2 3 4 5";
istringstream iss(s);
while (iss)
{
string t;
iss >> t;
if (!t.empty())
{
cout << pow(stoi(t), 2) << endl;
}
}
}