c++ converting string to int

前端 未结 4 611
我在风中等你
我在风中等你 2021-01-28 06:55
//sLine is the string
for(int l = 0; l < sLine.length(); l++)
{
    string sNumber;
    if(sLine[l] == \'-\')
    {   
        sNumber.push_back(sLine[l]);
        sN         


        
4条回答
  •  醉话见心
    2021-01-28 07:26

    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).

提交回复
热议问题