STring to int

closed account (NUj6URfi)
How do you convert a string to an int if the string is a number?
What sort of string? An STL std::string? A C-style character array? Some other string class?
closed account (NUj6URfi)
A string from a txt document.
Yes, but how are you storing that sting in your code? An STL std::string? A C-style character array? Some other string class?
closed account (NUj6URfi)
I'm saying x = xlocation.txt; x is a int
Last edited on
Not sure if trolling...?
closed account (NUj6URfi)
what do you mean?
closed account (NUj6URfi)
The error is

invalid conversion from `const char*' to `int'
So you're using C-style char arrays to store the string, then. Why couldn't you just tell me that in the first place?

You can use the std::atoi() function. I believe there's documentation for the function on this site.
How is xlocation.txt defined?
closed account (NUj6URfi)
I opened it in ifstream
closed account (NUj6URfi)
I do not understand the atoi documentation :(
Are you using a text file to store variable data in an attempt to create a "save game" file?

And now you want to pull that data back out from the text file to create a "load game" feature.

Try something like this...

1
2
3
4
5
6
7
8
9
10
11
12
string line; //create a string variable called line.
int myNumber; //create an int variable
ifstream gamefile;
gamefile.open ("xlocation.txt");
if(gamefile.is_open()) {

	    getline(gamefile, line);
	    stringstream myStream(line);
	    myStream >> myNumber;
}
gamefile.close();
cout << myNumber; // to see if it worked 


remember to include all needed library files like <string> for example.

Topic archived. No new replies allowed.