开发者

Convert a number from string to integer without using inbuilt function

I am trying this technique but error is coming. Please help me to convert a number from string to integer.

#include<iostream>
using namespace std;

int main()
{
    char *buffer[80];
    int a;

    cout<<"enter the number";
    cin.get(buffer,79);

    char *ptr[80] = &buffer;
    while(*ptr!='\0')
    {
        a=(a*10)+(*ptr-48);
    }
    cout<<"the value"<<a;

    delete ptr[];

    return 0;
}

Errors are:

  1. err开发者_开发技巧or C2440: 'initializing' : cannot convert from 'char ()[80]' to 'char *[80]'
  2. error C2440: '=' : cannot convert from 'char *' to 'int'


When you define variables as "char *buffer[80]", you are actually making an array of 80 char pointers instead of an array of size 80. Also, you shouldn't delete anything that was not allocated using new (or delete[] anything that wasn't allocated with new[], in this case).

EDIT: Another thing, you're not actually advancing ptr, so you'll always be looking at the first character.


As @Tal has mentioned, you are creating buffers of char* but you treat them like buffers of char. However, the recommended C++ way is not to use raw buffers at all:

#include<iostream>
#include <string>
using namespace std;

int main()
{
    string buffer;
    int a = 0;

    cout<<"enter the number";
    cin >> buffer;

    for(string::iterator it = buffer.begin(); it != buffer.end(); ++it)
    {
        a=(a*10) + (*it-48);
    }
    cout<<"the value"<<a;

    return 0;
}

Of course, this can be shortened to:

#include<iostream>
using namespace std;

int main()
{
    int a;

    cout<<"enter the number";
    cin >> a;
    cout<<"the value"<<a;
}

But that already uses library functions.

EDIT: Also fixed int anot being initialized. That caused your program return garbage.


Below will help. I am using this way in my projects.

bool stringToInt(std::string numericString, int *pIntValue)
{
    int dVal = 0;
    if (numericString.empty())
        return false;

    for (auto ch : numericString)
    {
        if (ch >= '0' && ch <= '9')
        {
            dVal = (dVal * 10) + (ch - '0');
        }
        else
        {
            return false;
        }
    }

    *pIntValue = dVal;
    return true;
}

int main()
{
    int num = 0;
    std::string numStr;
    std::cin >> numStr;
    if (!stringToInt(numStr, &num))
        std::cout << "convertionFailed\n";
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜