将字符串元素转换为整数 (C++11)
Convert string element to integer (C++11)
我正在尝试使用 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
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;
有人知道我的代码有什么问题吗?
问题是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 中大于个位数的数字,因为 for 循环方法会中断大于 9 的数字。
如果您使用std::string
,stoi()
可以正常工作。 所以
string a = "12345";
int b = 1;
cout << stoi(a) + b << "n";
将输出:
12346
因为,在这里你传递一个char
你可以使用以下代码行来代替你在 for 循环中使用的代码行:
std::cout << std::pow(s[i]-'0', 2) << "n";
像这样:
#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;
}
}
}
相关文章:
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- C++11 标准是否保证零值有符号整数的一元减号为零?
- 如何在 C++11 编译时构建具有递增值的整数成员的结构序列
- 累积从 C++11 中的文件中读取数据的整数
- 在 C++11 中打印编译时整数序列
- C++11 整数初始化
- C++11 中是否有实际的 4 位整数数据类型
- 将字符串元素转换为整数 (C++11)
- 无法在 c++ 中声明动态整数数组,可能是 c++11 错误
- C++输入超过 11 个整数时程序终止
- 在C++11中实现共享整数计数器而不使用互斥的最简单方法:
- 如何使用 C++11 实现指向整数的指针的原子增量<atomic>?
- 是否可以定义一个 C++11 可变参数类模板,其可变参数基数取决于整数模板参数
- C++11 为什么 cout 从布尔数组打印大整数
- C++11 编写模板以选择更大的整数类型的方法
- 通过单行中的XOR交换整数.在c++11中真的允许这样做吗
- C++11 中的"auto var = {condition} ? 1 : 1.0"是什么类型?是双精度还是整数?
- C11/C++11 宏,用于将常量字符串与文本整数相关联
- 左移 (<<) 是 C++11 中未定义行为的负整数吗?
- 如何将整数转换为std::u16string(C++11)