Converting a string from getline() to an int

Hi!

Me and my friends are quite new in programming but we have decided to increase them by making a game project.

We have gotten up to the point where we want to load data from a file into the objects we use to represent the map.

However we use integers for our data in the objects and the ifstream::getline() returns a string. So we need to convert that string(which is all numerical) to an int.

the code so far:

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
Cell cellMap[1000]
void LoadCells()
{

     ifstream Cellfile;
     string line;
     int a,b=0;
     Cellfile.open ("Cells.txt");
     if (Cellfile.fail())   // this checks if it load right?
     {
        cout << "failed load"; 
        return;
        }
     
     else{
          while(getline(Cellfile,line))
          {
          cellMap[b].Setpop(line); // this input needs to be numerical
          getline(Cellfile,line); // this skips to the next line, correct?
          cellMap[b].Setbuildings(line);// 
          ++b;
          }
     
     }
     return;
}

the only thing the compiler is complaining about is the fact that the functions Setbuildings() and Setpop() only takes integers.

Or is there a better way to resolve this issue?

Thankful for an answer.
Last edited on
try this

1
2
3
4
5
6
7
8
9
ifstream Cellfile;
Cellfile.open("Cells.txt");

vector<int> cellmap;
int temp = 0;

while (!Cellfile.eof()) {
	Cellfile >> temp;
	cellmap.push_back(temp);}
Have you tried sstream?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
	int YourNumber = 0;
	string FileContents = "34354";
	stringstream (FileContents) >> YourNumber;
	cout << YourNumber << endl;
	cin.get ();
	return 0;
}

Number Validation:
http://www.cplusplus.com/forum/beginner/48104/#msg261220
Works like a charm, thank you.
PS: Didn't see that post when I searched, sry.
Topic archived. No new replies allowed.