如何在C ++中使用std :: stoi将c字符串转换为整数

问题描述 投票:0回答:2

假设我有一个C字符串样本如下:

"-fib 12"
"-fib 12"
"-e 2"
"-pi 4"

我想使用std :: stoi函数将C字符串中的最后一个数字转换为整数变量。我以前从未使用过stoi功能,试图让它工作起来相当混乱。谢谢!

c++ linux g++ c-strings
2个回答
1
投票

您必须首先通过空格字符之前的非数字数据才能使用std::stoi

char* s = "-fib 12";

// Skip until you get to the space character.
char* cp = s;
while ( *cp != ' ' && *cp != '\0') cp++;

// Defensive programming. Make sure your string is not
// malformed. Then, call std::stoi.
if ( *cp == ' ' )
{
   int num = std::stoi(cp);
}

0
投票

使用std :: string,你也可以做...

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "15";
    std::string str2 = "3.14159";
    std::string str3 = "714 and words after";
    std::string str4 = "anything before shall not work, 2";
    int myint1 = std::stoi(str1);
    int myint2 = std::stoi(str2);
    int myint3 = std::stoi(str3);

    // int myint4 = std::stoi(str4); // uncomment to see error: 'std::invalid_argument'
    std::cout << myint1 << '\n'
              << myint2 << '\n'
              << myint3 << '\n';
    //  << myint4 << '\n';
}

产量

15
 3 //discarded the decimal portion since it is int
714 // discarded characters after the digit
© www.soinside.com 2019 - 2024. All rights reserved.