学习相关知识,耗时 1 小时

Str2Int Str2UInt Str2ULongLong Str2Double Int2String ……
stoi stof stod stoll stoull to_string
// 以下是 www.cplusplus.com 对 stoi 的说明int stoi (const string& str, size_t* idx = 0, int base = 10);int stoi (const wstring& str, size_t* idx = 0, int base = 10);Convert string to integerParses str interpreting its content as an integral number of the specified base,which is returned as an int value.If idx is not a null pointer,the function also sets the value of idx to the position of the first character in str after the number.
atoi atof atol atoll
// 以下是 www.cplusplus.com 对 atoi 的说明int atoi (const char * str);Convert string to integerParses the C-string str interpreting its content as an integral number,which is returned as a value of type int.The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found.Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
stoi 的入参是 string,atoi 的入参是 c-string(char*) atoi 会处理前面多余的空格 atoi 的入参如果不是一个数字型,会返回 0
string s = " 10a";cout << "s:" << stoi(s) << endl; // 10cout << "s:" << atoi(s.c_str()) << endl; // 10s = "";// cout << "s:" << stoi(s) << endl; corecout << "s:" << atoi(s.c_str()) << endl; // 0s = " ";// cout << "s:" << stoi(s) << endl; corecout << "s:" << atoi(s.c_str()) << endl; // 0s = " a10";// cout << "s:" << stoi(s) << endl; corecout << "s:" << atoi(s.c_str()) << endl; // 0
第一个非空字符是数字,stoi 和 atoi 都能成功转换 第一个非空字符不是数字,stoi 会 core 掉,atoi 返回 0
try{int i = boost::lexical_cast<int>("1");}catch (boost::bad_lexical_cast&){continue;}
文章转载自每天一个开发小知识,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




