如何将c++str转换为int
how can i convert c++ str to int?
可能重复:
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
}
为什么不立即读取整数?
int num;
cin >> num;
您不需要有两个变量。在C++中,在输入流,而从未将文本视为字符串。所以你可以简单地写:
int num;
std::vector< int > product( 10 );
std::cout << "enter number: ";
std::cin >> num;
...
请注意,我已经更正了您将数组声明为好您通常不会在C++中使用int product[10];
。(你几乎永远不会在同一行定义两个变量,即使语言允许。)
到目前为止,转换为字符串并返回的最简单方法是使用转换函数。
std::string s="56";
int i=std::stoi(s);
http://en.cppreference.com/w/cpp/string/basic_string/stol
和背面
int i=56;
std::string s=std::to_string(i);
http://en.cppreference.com/w/cpp/string/basic_string/to_string
当然,如果你正在阅读输入,你也可以在那里阅读
int i;
std::cin >> i;
这是一个完整的示例:
//library you need to include
#include <sstream>
int main()
{
char* str = "1234";
std::stringstream s_str( str );
int i;
s_str >> i;
}
如果您绝对必须使用std::string
(出于任何其他原因…可能是家庭作业?),那么您可以使用std::stringstream
对象将其从std::string
转换为int
。
std::stringstream strstream(num);
int iNum;
num >> iNum; //now iNum will have your integer
或者,您可以使用C中的atoi
函数来帮助您使用
std::string st = "12345";
int i = atoi(st.c_str()); // and now, i will have the number 12345
所以你的程序应该看起来像:
vector<string> num;
string holder;
int num_int, product[10];
cout << "enter numbers";
for(int i = 0; i < 10; i++){
cin >> holder;
num.push_back(holder);
}
for(int i =0; i<10; i++){
product[i] = atoi(num[i].c_str()) * 5; //I need the int value of num*5
}
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度