File I/O Onto Variables

Ok, I am trying to write a bit of code that takes data from a file and uses it directly in the code. Here is a piece of code where only one line can be stored at a time and it is as a string. I want all the lines to be stored and as an integer. Can anyone help?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

  int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
Try this:

1
2
3
4
getline(myfile, line);
int num = atoi(line.c_str);
cout << num << endl;
cout << num*2 << endl;


References:
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
http://www.cplusplus.com/forum/general/13135/
http://www.cplusplus.com/forum/articles/9645/
1
2
3
4
5
6
7
8
9
10
ifstream myfile ("example.txt");
if (myfile.is_open())
{
	int value;
	while (myfile >> value)
	{
		cout << value << endl;
	}
}
else cout << "Unable to open file";
Last edited on
Is any way to get more than one number? Peter87
Use an array or vector.

1
2
3
4
5
6
7
8
9
std::ifstream myfile ("example.txt");
std::vector<int> values;

int temp;
while(myfile >> temp)
{
  values.push_back(temp);
  std::cout << values.last() << std::endl;
}
Last edited on
Topic archived. No new replies allowed.