Convert string to int

May 6, 2011 at 12:08pm
Hello everyone

Could anyone please tell why does the following code not convert the string into int? When I pass a hard coded string e-g "123456" then the code below works, but when I pass a string element from a string type vector, the code doesn't work.

class.h
1
2
3
4
5
class cls
{
	public:
	template <class T> bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&)); 
};

class.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

template <class T> bool cls::from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&))
{
	std::istringstream iss(s);
	return !(iss >> f >> t).fail();
}

void cls::somefunct()
{
	int i;
	string strn = vector[1];
	if(from_string(i, std::string(strn), std::dec))
	{
		std::cout << "i: " << i << std::endl;
	}
	else
	{
		std::cout << "from_string failed" << std::endl;
	}
}
Last edited on May 6, 2011 at 12:46pm
May 6, 2011 at 12:31pm
1
2
string str;
int i = atoi( str.c_str() );


is easier, but if you insist on C++, you should correct Lines 8 and 11.
There may be other errors, but that's what I eyeball atm.
May 6, 2011 at 12:53pm
Thanks kfmfe04

I've also tried this but the result is not what I want.
1
2
3
4
5
6
7
vector[1] = "00181170323230"

string str = vector[1];

int i = atoi( str.c_str() );

cout << "atoi: " << i << endl;


result is
atoi: 781696798
May 6, 2011 at 1:08pm
well, I hope you realize that a C/C++ int does not have infinite precision.

if you intend to pass in strings that big, then:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <string>
#include <iostream>

using namespace std;

static vector<string> vec;

main()
{
  vec.push_back( "00181170323230" );
  long l = strtol(vec[0].c_str(), (char **)NULL, 10);
  cout << "strtol: " << l << endl;
}


strtol: 181170323230


NOTE: also, if you are using an STL vector, realize that it is 0-based and not 1-based. Also, you will have to use push_back() to insert values, if the vector started off empty. Please read up on stl vectors, but if you already know all this, then you can ignore me.
Last edited on May 6, 2011 at 1:10pm
May 6, 2011 at 1:20pm
Thanks a lot. That worked and thanks for all your suggestions :-).

vector[1] = "00181170323230" was just an example to show that index [1] holds "00181170323230" value.

THANKS
May 6, 2011 at 1:36pm
np - btw, there are some C++ purists who will only use C++ constructs - I'm not one of them =)

gl w/your coding
May 6, 2011 at 1:49pm
Thank you (:-)
Topic archived. No new replies allowed.