c++ converting string to int

守給你的承諾、 提交于 2019-12-20 06:38:11

问题


//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;
}

I have this for-loop which checks each character of the string and converts every number in this string to be a int. But for some reason, the atoi function is doing it twice so when I cout it, it displays it twice for some reason... Why is that?

example: INPUT 3 3 -3 9 5
-8 -2 9 7 1
-7 8 4 4 -8
-9 -9 -1 -4 -8

OUTPUT 3030-309050 -80-20907010
-70804040-80
-90-90-10-40-80


回答1:


It's displaying a zero for all nonrecognized characters, because atoi returns 0 when given a non-numeric string (like a space!)

However, what you want to do, is shockingly simple:

std::stringstream ss(sLine);
int num;
while(ss >> num) {
    cout << num;
}



回答2:


Move this:

const char* testing = sNumber.c_str();
int num = atoi(testing);
cout << num;

Below the last } in the code you pasted, i.e. out of the for-loop. Currently you get a separate printout for every character in sLine because it's executed on every iteration of the loop. (The last character in sLine may be a linefeed so this can occur even if you think you wrote only one digit.)

Edit: Also move the declaration of sNumber above the for-loop.

You may also want to change if (sLine[l] == '-') to if (sLine[l] == '-' && (l + 1) < sLine.length()) so you don't access beyond the end of the string if the dash is the final character on the line.

You may also want to rename the variable l to something that looks less like a 1. =)

You may also want to rethink if this is the right way to do this at all (usually if a simple thing gets this complicated, chances are you're doing it wrong).




回答3:


You output extra 0 for the characters which are not digits. The problem is that atoi returns 0 when it cannot convert the input, so your whitespaces are printed as zeroes.




回答4:


That seems like a painful way to recreate the wheel. You'd be better off using a stringstream to parse this.

std::stringstream strm(sLine);
int num;
while(strm >> num)
{
    std::cout << num << std::endl;
}


来源:https://stackoverflow.com/questions/8014387/c-converting-string-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!