Duoas correct me if I'm wrong but ill take a shot at this...
A string in C++ is a char array, so you will have to break down each char of the string into and array of the string and use a for loop to convert the ASCII to int, and add the values together. In C++ there is a dandy little function called atoi() which stands for ASCII to integer. That should help you get an idea of the direction you need to go to. :) Hope this helped
Sigh, all these confusing char arrays to strings and loops to make it integers, why can't there just be a function that does all of this for us? Something like: S2I( myString ); ?
Also, hartmanr76, could you provide an example? The one provided in the atoi() documentation is a bit confusing, and uses different methods for printing etc than I do.
Alright so digging through some old programs I found atoi is generally for allowing you to read in a number from a char and let it become an int... Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
char chrbuffer[80] = {0};
int intNumber = 0;
cout << "Please enter a number: ";
cin.getline(chrbuffer,80);
intNumber = atoi(chrbuffer);
if(intNumber % 2 == 0)
{
cout << "Your number is even\n";
}
else
{
cout << "Your number is odd\n";
}
this will allow you to input a number into the console and it will display the number instead of its value (i.e. input = 1, output = 1)
this code will actually convert anything to its value (i.e. input = 1; output = 49)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int _tmain()
{
char input[80] = {0};
int i = 0;
int total = 0;
cout << "Please enter something you would like to convert: ";
cin.getline(input,80);
for(int j = 0; j < 80; j++)
{
i = input[j];
total += i;
}
cout << total << endl;
return 0;
}
this will also allow you to type up to 80 char's and will convert everything and add it all up...
Wow, if you want to split hairs, at least qualify yourself:
A C++ string is an STL container that automatically manages a dynamic array of char for you.
Hence, underneath it really is an array of char --but it is infinitely easier to use.
atoi() is the simplest conversion routine you can use. Its limits are:
- limited to signed int
- no useful error handling
strtol() and strtoul() were invented to do it better:
- signed or unsigned
- exacting error handling --which you can use to recover from failures in stream operations
In C++, the stringstream class does it all for you:
#include <ciso646>
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
int main()
{
int age = -1;
string name;
int fooey();
cout << "Please enter your first name and your age (in any order)> ";
string line;
if (!getline( cin, line ) or line.empty())
return fooey();
istringstream ss( line );
if (ss >> age)
{
ss >> name;
}
else
{
ss.clear();
ss >> name;
ss >> age;
}
if (ss.fail() or name.empty())
return fooey();
cout << "Your name is " << name << " and you are " << age << " years old.\n";
return 0;
}
int fooey()
{
cout << "You failed.\n";
return 1;
}