Help me find the error

Hello guys, please help me find the error in the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<class T> int to_int(const T& t)
{
	ostringstream os;
	int num = 0;

	os << t;

	string str = os.str();

	for (int i = 0; i < (int)str.length(); i++)
	{
		num += to_dig(str[i]) * pow(10, (int)str.length() - 1 - i);
	}

	return num;
}


Don't worry about to_dig(char), I wrote it to convert a character to a digit to facilitate the process.

The code is acctualy working fine but the compiler shows this warning:
1
2
3
4
5
note: see reference to function template instantiation 'int to_int<char[4]>(const T (&))' being compiled
1>        with
1>        [
1>            T=char [4]
1>        ]
Last edited on
You have only posted the part that tells us where the warning is. It would be useful if you also posted the part that says what the warning is about.
warning C4244: '+=': conversion from 'double' to 'int', possible loss of data
I didn't see it I just had to convert it to int like so
 
num += to_dig(str[i]) * (int)pow(10, (int)str.length() - 1 - i);


Thanks ^^
Last edited on
Normally people just say:

 
    num = num * 10 + to_dig(str[i]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Example program
#include <iostream>
#include <sstream>
#include <string>

template <class T>
int to_int(const T& t)
{
	std::stringstream ss;
	ss << t;
	
	// probably wanna do some sort of error checking...
	int num = 0;
	ss >> num;
	return num;
}

struct Foo {};

std::ostream& operator<<(std::ostream& os, const Foo& foo)
{
    return os << 42;
}

int main()
{
    int a = to_int("90");
    int b = to_int(Foo());
    std::cout << a << " " << b << std::endl;
}
Last edited on
Topic archived. No new replies allowed.