[英]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.