如何将c++str转换为int

how can i convert c++ str to int?

本文关键字:int 转换 c++str      更新时间:2023-10-16

可能重复:
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
}