繁体   English   中英

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

[英]How to convert a c string to an integer using std::stoi in C++

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

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

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

您必须先std::stoi非数字数据,然后才能使用空格字符才能使用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);
}

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM