assigning string to int

B

Ben

Hi all,

I would like to know if there is an easy way to assign a string to an int.

I have a struct such as:

struct Values {
int a;
int b;
}

I have 2 strings that i read from a file:
string x = "12";
string y = "10";

Now I'd like to do something like this:
Values val;
val.a = x;
val.b = y;

There is of course a mis-match.. How do I fix it? Is there an easy way?

Thanx for help!
Ben
 
M

Mike Wahler

Ben said:
Hi all,

I would like to know if there is an easy way to assign a string to an int.

No, those two types are not 'compatible'. However
(as is what it appears you're really asking, yes
you can convert the textual representation of an
integer (i.e. a sequence of digit characters) to
an integer type.)
I have a struct such as:

struct Values {
int a;
int b;
}

I have 2 strings that i read from a file:
string x = "12";
string y = "10";

Now I'd like to do something like this:
Values val;
val.a = x;
val.b = y;

There is of course a mis-match.. How do I fix it? Is there an easy way?

There are a few ways, which is 'easy' is a matter of opinion.
Then there are also opinions about which is 'better'.

One way is to use a stringstream
(you'll need to #include <sstream>
to use one):

std::istringstream iss(x + ' ' + y);
iss >> val.a >> val.b;

For a (imo) more flexible, 'robust' method, look up the
'strtol()' function, declared by <cstdlib>

-Mike
 
P

Petec

Ben said:
Hi all,

I would like to know if there is an easy way to assign a string to an
int.

I have a struct such as:

struct Values {
int a;
int b;
}

I have 2 strings that i read from a file:
string x = "12";
string y = "10";

Now I'd like to do something like this:
Values val;
val.a = x;
val.b = y;

There is of course a mis-match.. How do I fix it? Is there an easy
way?

Thanx for help!
Ben


template<typename T, typename TCHAR>
T fromstring(const std::basic_string<TCHAR>& s)
{
std::basic_istringstream<TCHAR, std::char_traits<TCHAR>,
std::allocator<TCHAR> > iss(s);
T x;
iss >> x;
if(!iss)
throw std::invalid_argument("Bad argument!");
return x;
}

template<typename T, typename TCHAR>
std::basic_string<TCHAR> tostring(const T& x)
{
std::basic_ostringstream<TCHAR, std::char_traits<TCHAR>,
std::allocator<TCHAR> > oss;
oss << x;
if(!oss)
throw std::invalid_argument("Bad argument!");
return oss.str();
}

val.a = fromstring<int, char>(x);
val.b = fromstring<int, char>(y);

fromstring() can be used in a similar way.

- Pete
 
P

Petec

Petec wrote:
template<typename T, typename TCHAR>
std::basic_string<TCHAR> tostring(const T& x)
{
std::basic_ostringstream<TCHAR, std::char_traits<TCHAR>,
std::allocator<TCHAR> > oss;
oss << x;
if(!oss)
throw std::invalid_argument("Bad argument!");
return oss.str();
}

val.a = fromstring<int, char>(x);
val.b = fromstring<int, char>(y);

fromstring() can be used in a similar way.
 
J

JKop

Ben posted:
Hi all,

I would like to know if there is an easy way to assign a string to an
int.

I have a struct such as:

struct Values {
int a;
int b;
}

I have 2 strings that i read from a file:
string x = "12";
string y = "10";

Now I'd like to do something like this:
Values val;
val.a = x;
val.b = y;

There is of course a mis-match.. How do I fix it? Is there an easy way?

Thanx for help!
Ben

First of all, I'd like to explain what's happening. Take the following:

"12"

What this is, is three char's side by side in memory:

char twelve[3];

twelve[0] = 31; //'1' = 31 The ASCII keycode
twelve[1] = 32; //'2' = 32
twelve[2] = 0; //'\0' = 0


What you're trying to do is allot more complicated than you think! You need
a function that wil see that 32 == 2 and then see that 31 == 1 * 10, see
what I mean. If I were to write such a function, I'd do it something like
so:

UNTESTED CODE

unsigned long int GenerateNumber(const char* pString)
{
unsigned long int Number;

while (pString += 1)
{
;
}

//We've found the terminating null character

pString -= 1;
//Now we're at the last digit


Number = *pString - '0';
//This gets the actual number from the ASCII keycode


//Now go to the second last digit
pString -= 1;

//This time it's to be multiplied by 10
Number += ( ( *pString - '0' ) * 10 );


//You'd use a loop to go through all the digits,
//then you'd:

return Number;
}


But ofcourse, there's reusable code already there to do this for you. I
myself am not familiar with the "string" class, so some-one else will have
to give you a hand with that.


Hope the explanation gives you some in-sight in anyway.

-JKop
 
D

DigitaluX

Op Sat, 29 May 2004 09:48:55 -0700, schreef Ben:
Hi all,

I would like to know if there is an easy way to assign a string to an int.

I have a struct such as:

struct Values {
int a;
int b;
}

I have 2 strings that i read from a file:
string x = "12";
string y = "10";

Now I'd like to do something like this:
Values val;
val.a = x;
val.b = y;

There is of course a mis-match.. How do I fix it? Is there an easy way?

Thanx for help!
Ben

You can use the function itoa ;-)

val.a = itoa(x);
 
D

DigitaluX

Op Sat, 29 May 2004 09:48:55 -0700, schreef Ben:
Hi all,

I would like to know if there is an easy way to assign a string to an int.

I have a struct such as:

struct Values {
int a;
int b;
}

I have 2 strings that i read from a file:
string x = "12";
string y = "10";

Now I'd like to do something like this:
Values val;
val.a = x;
val.b = y;

There is of course a mis-match.. How do I fix it? Is there an easy way?

Thanx for help!
Ben

EUH, it was atoi not itoa :-(

val.a = atoi(x);
 
P

Petec

DigitaluX wrote:
EUH, it was atoi not itoa :-(

val.a = atoi(x);

Aside from atoi() having no error detection, you example will not compile.
If you must use atoi(), this will work:
val.a = atoi(x.c_str());

I highly reccomend staying away from it, though.

- Pete
 
D

DigitaluX

Op Sat, 29 May 2004 21:48:51 +0000, schreef Petec:
DigitaluX wrote:



Aside from atoi() having no error detection, you example will not compile.
If you must use atoi(), this will work:
val.a = atoi(x.c_str());

I highly reccomend staying away from it, though.

- Pete

You are totaly right, forgot the c_str() :-$.

Why should a programmer stay away from this?
 
P

Petec

DigitaluX said:
Op Sat, 29 May 2004 21:48:51 +0000, schreef Petec:


You are totaly right, forgot the c_str() :-$.

Why should a programmer stay away from this?

No error handling is possible. If you pass in, for example, "one two three",
the results of atoi will be zero, which is impossible to tell from a
legitimate zero.

- Pete
 
B

Ben

Mike Wahler said:
There are a few ways, which is 'easy' is a matter of opinion.
Then there are also opinions about which is 'better'.

One way is to use a stringstream
(you'll need to #include <sstream>
to use one):

std::istringstream iss(x + ' ' + y);
iss >> val.a >> val.b;

For a (imo) more flexible, 'robust' method, look up the
'strtol()' function, declared by <cstdlib>

-Mike

using istringstream gave me following error:
variable `std::istringstream iss' has initializer but incomplete
type

i'm not sure what it means. i'm not very familiar with
istringstream... i'm using gcc compiler version 3.2 in Linux.

Thanx!
Ben
 
R

Robert Bauck Hamar

unsigned long int GenerateNumber(const char* pString)
{
unsigned long int Number;

while (pString += 1)
{
;
}

//We've found the terminating null character

pString -= 1;
//Now we're at the last digit


Number = *pString - '0';
//This gets the actual number from the ASCII keycode


//Now go to the second last digit
pString -= 1;

//This time it's to be multiplied by 10
Number += ( ( *pString - '0' ) * 10 );


//You'd use a loop to go through all the digits,
//then you'd:

return Number;
}

Instead of working backwards, try to work forward. To see how, assume
we call GenerateNumber("123"). GenerateNumber will enter the for loop,
finding that '1' is a digit. The result will then be 1 after the first
iteration. Then it finds that '2' is a digit, and multiplies result by
ten, giving 10, and adds the two, giving 12. The multiplication will
then produce 120, and the addition 123. It terminates when finding '\0'
is not a digit. Please do not write code before you think.

#include <cctype>

unsigned long int GenerateNumber(const char* number)
{
unsigned long int result = 0;

for (; std::isdigit(*number); ++number) { //loop through the digits
//The result is multiplied by 10 to make the last
//digit in result a zero.
result *= 10;

//Add the next digit
result += *number - '0';
}

return result;
}
 
M

Michael Schutte

Ben said:
Hi all,

I would like to know if there is an easy way to assign a string to an int.

You can do it the C way (atoi()) or the other C way (sscanf()):

std::string s = "12";
int x;
if (std::sscanf(s.c_str(), "%d", &x) < 1)
std::cerr << "int parsing failed";
else
; // Success! (12 stored in x)

You have to #include <cstdio> for that.
 
W

William Xuuu

using istringstream gave me following error:
variable `std::istringstream iss' has initializer but incomplete
type

i'm not sure what it means. i'm not very familiar with
istringstream... i'm using gcc compiler version 3.2 in Linux.

Thanx!
Ben

Mike has reminded you to include<sstream> first.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top