If i have a set of numbers:
48098, 50933, 3128, 323, 42, 5..etc

how can i convert them into integers? I have an example of a code (see below) that will convert one number, not the whole set. So, im having trouble trying to convert a set of numbers seperated by commas into integers.

*NOTE - im reading a .txt file from wordpad using "fstream"

Here is the example of the code:

``````#include <sstream>
#include <string>
#include <iostream>

using namespace std;

bool StringToInt(const string &s, int &i);

int main(void)
{
string s1 = "12";
string s2 = "ZZZ";
int result;

if (StringToInt(s1, result))
{
cout << "The string value is " << s1
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed" <<endl;
}
if (StringToInt(s2, result))
{
cout << "The string value is " << s2
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed on " <<s2 <<endl;
}
return(0);
}

bool StringToInt(const string &s, int &i)
{
istringstream myStream(s);

if (myStream>>i)
return true;
else
return false;
}``````

you can use strtok() -- warning, that function changes the string, so if you need the original string later in the program you will have to make a copy of it before calling strtok() the first time.

``````std::string str = "48098, 50933, 3128, 323, 42, 5";
int n;
char* ptr = strtok((char*)str.c_str(),",");
while(ptr != 0)
{
n = atoi(ptr); // you will probably want to put the ints into
// some sort of array or vector
ptr = strtok(0,",");
}``````

Thanks for the code....however, i kept on getting errors for some reason...so i kind of manipulated it and came out with this code, and it worked out pretty well...what helped was knowing strtok().

Here's the code:

``````#include <string.h>
#include <stdio.h>

char string[] = "48098,50933,3128,323,42,5";
char seps[]   = " ,";
char *token;

void main(void)
{
printf( "%s\n\n Tokens:\n", string);

token = strtok( string, seps );

while( token != NULL )
{
printf( "%s\n", token );

token = strtok( NULL, seps );
}
}``````

Thanks again.

If the current protocol is satisfactory for you, so be it. You might also be able to accomplish essentially the same thing by processing each number as you read it in, rather than read in all the numbers at once and parse the whole file/string. To do that, I'd use getline() with comma as the delimiting character to read a string representing a single number into a buffer and convert the buffer on the fly. This approach might work better if you don't know the number of numbers or the number of digits in the numbers you're going to need to hold the composite string and you aren't hardcoding the string but reading it on the fly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.