String to Long Long

Hey guys.

I am writing a program and one of the functions that I need to write is supposed to convert a string to type longlong. I am having quite a difficult time doing this. If someone could help me get started I can probably figure it out from there.

Thanks so much in advance!

This is my function definition:
 
longlong strtolonglong(string s)
Also. I do not know if this is going in the right direction but I was thinking of subtracting character 0 from my string. I do not know if that is the correct way or not. The code would look like this.

1
2
3
4
5
6
longlong strtolonglong(string s)
{
     int longlong;
     longlong = s - '0';
     return longlong;
}


p.s. in addition to this code, my professor has included this code at the beginning of the program. I do not know if this matters or not. He has not told us what it does..

1
2
3
4
5
#if defined(WIN32)
typedef __int64 longlong;
#else
typedef long long longlong;
#endif 
Last edited on
You can check if the string is an valid number (ie, contains optional +- at the beginning and just symbols '0'-'9').

To convert from digit symbol to number you can use:
int(digit - '0');

And note that
314 = 3*100 + 1*10 + 4 = ((3)*10 + 1)*10 +4.
Instead of
1
2
3
4
5
6
longlong strtolonglong(string s)
{
     int longlong;
     longlong = s - '0';
     return longlong;
}

should be
1
2
3
4
5
6
longlong strtolonglong(string s)
{
     longlong result;
     result = s[0] - '0';
     return result;
}


It will return the first digit.
Last edited on
The string is actually already predefined in my program. My string is defined as follows:

1
2
3
4
5
6
7
8
9
10
string e = "2718281828459045235360287471352662497757247093699959574966967"
	"6277240766303535475945713821785251664274274663919320030599218174"
	"1359662904357290033429526059563073813232862794349076323382988075"
	"3195251019011573834187930702154089149934884167509244761460668082"
	"2648001684774118537423454424371075390777449920695517027618386062"
	"6133138458300075204493382656029760673711320070932870912744374704"
	"7230696977209310141692836819025515108657463772111252389784425056"
	"9536967707854499699679468644549059879316368892300987931277361782"
	"1542499922957635148220826989519366803318252886939849646510582093"
	"9239829488793320362509443117";
Last edited on
It is too long to fit into 8 bytes.
Well I am breaking it up into 10 digit parts. I have added a for-loop to your code in hopes to read each 10 digit section into my variable result however, each time it goes through the loop only the one digit is assigned to result. Is there a way to add them like you would have result end up being a 10 digit sequence of numbers? I feel like I probably have done this before I just can not seem to find my previous code.

1
2
3
4
5
6
7
8
9
longlong strtolonglong(string s)
{
	longlong result;
	for(int i = 0; i < e.length() - 10; i++)
	{
		result = s[0] - '0';
	}
	return result;
}
Topic archived. No new replies allowed.