僅使用C++設施簡單且類型安全的解決方案是以下方法:
#include <iostream>
#include <sstream>
int fromString(const std::string& s)
{
std::stringstream stream;
stream << s;
int value = 0;
stream >> value;
if(stream.fail()) // if the conversion fails, the failbit will be set
{ // this is a recoverable error, because the stream
// is not in an unusable state at this point
// handle faulty conversion somehow
// - print a message
// - throw an exception
// - etc ...
}
return value;
}
int main (int argc, char ** argv)
{
std::cout << fromString ("123") << std::endl; // C++03 (and earlier I think)
std::cout << std::stoi("123") << std::endl; // C++ 11
return 0;
}
注意:在fromString()
你應該檢查,看看是否該字符串的所有字符實際上形成一個有效的積分值。例如,GH1234
或其他東西不會,並且調用operator>>
後值將保持爲0。
編輯:只記得,檢查轉換是否成功的簡單方法是檢查流的failbit
。我相應地更新了答案。
這隻適用於數字,你應該減去''0'。 – chris
可能的重複[如何解析一個字符串到一個int在C + +?](http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c) – villintehaspam
這個問題是類似的,並且大多數答案將適用:http://stackoverflow.com/questions/1012571/stdstring-to-float-or-double –