【发布时间】:2011-11-04 18:55:03
【问题描述】:
//sLine is the string
for(int l = 0; l < sLine.length(); l++)
{
string sNumber;
if(sLine[l] == '-')
{
sNumber.push_back(sLine[l]);
sNumber.push_back(sLine[l + 1]);
l++;
}
else if(sLine[l] != '\t')
{
sNumber.push_back(sLine[l]);
}
const char* testing = sNumber.c_str();
int num = atoi(testing);
cout << num;
}
我有这个 for 循环,它检查字符串的每个字符并将该字符串中的每个数字转换为 int。但是由于某种原因,atoi 函数会执行两次,所以当我 cout 时,它会出于某种原因显示两次……这是为什么呢?
示例:
输入
3 3 -3 9 5
-8 -2 9 7 1
-7 8 4 4 -8
-9 -9 -1 -4 -8
输出
3030-309050
-80-20907010
-70804040-80
-90-90-10-40-80
【问题讨论】:
-
sNumber.push_back(sLine[l + 1]);可以访问超出字符串结尾。 -
@Vlad 但我把它放在那里是因为负数......
-
整个循环执行了两次。
-
您能否展示一个输出示例,用于某些输入?在不相关的注释中,使用
isdigit而不是检查'\t',以防万一。 :) -
std::string s = "45"; int i = boost::lexical_cast<int>(s);顺便说一句