3

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

5 回答 5

5

为什么不直接读取整数?

int num;
cin >> num;
于 2013-02-05T19:12:00.667 回答
4

您不需要有两个变量。在 C++ 中,通常在输入流中即时转换,而不会将文本视为字符串。所以你可以简单地写:

int num;
std::vector< int > product( 10 );

std::cout << "enter number: ";
std::cin >> num;

...

请注意,我也更正了您声明数组的方式。您通常不会int product[10];在 C++ 中使用。(而且你几乎永远不会在同一行定义两个变量,即使语言允许。)

于 2013-02-05T19:13:44.377 回答
2

到目前为止,转换为字符串并再次转换回来的最简单方法是使用转换函数。

 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;
于 2013-02-05T19:42:39.960 回答
1

if you absolutely must use a std::string (for any other reason.. perhaps homework?) then you can use the std::stringstream object to convert it from a std::string to int.

std::stringstream strstream(num);
int iNum;
num >> iNum; //now iNum will have your integer

Alternatively, you can use the atoi function from C to help you with it

std::string st = "12345";
int i = atoi(st.c_str()); // and now, i will have the number 12345

So your program should look like:

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
}
于 2013-02-05T19:14:38.527 回答
1

这是一个完整的示例:

//library you need to include
    #include <sstream>
    int main()
    {
        char* str = "1234";
        std::stringstream s_str( str );
        int i;
        s_str >> i;
    }
于 2013-02-05T19:13:27.717 回答