[英]std::string part into integer
我有一個std :: string: 01001
,我想獲取每個數字:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
int res = atoi( foo[i] ); // fail
int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
怎么做?
這是我最簡單的方法:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
int res = foo[i] - '0';
}
如果您知道foo
所有字符都是數字,則可以使用(int) (foo[i] - '0')
從字符中減去ascii值'0'
。 這適用於所有數字,因為它們的ascii值是連續的。
您的第一次嘗試失敗,因為foo[i]
是單個char
,而atoi()
則使用cstring。 您的第二次嘗試失敗,因為&foo[i]
是對該字符的引用。
只需使用減法即可獲得每個數字:
int res = foo[i] - '0';
atoi
接受以零結尾的字符串,而不是單個字符。 減法之所以有效,是因為確保十個十進制數字在字符集中是連續的(顯然,如果字符串中可能包含非數字字符,則需要進行適當的錯誤處理)。
一種非常接近您所擁有的簡單方法是將char插入預定義的字符串中,如下所示:
std::string foo = "01001";
char str[] = {" "};
for (int i=0; i < foo.size(); ++i)
{
str[0] = foo[i];
int res = atoi( str );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.