Reputation: 105
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:
Upvotes: 1
Views: 2304
Reputation: 2373
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;
}
Upvotes: 0
Reputation: 15154
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 a
not being initialized. That caused your program return garbage.
Upvotes: 3
Reputation: 7317
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.
Upvotes: 5