Put intergers from textfile into arrays!

Im trying to put Intergers from textfile into array, and ive been writing a code for it but only works if i have intergers in textfile and not with characters and intergers.. What do i have to change?

Textfile can look like this (not working):
Chris Andersson
15
Theres Green
20

working:
20
54
...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 int *data;
 int num = 0;
  ifstream In("file.txt"); //
  if (In.good()) 
    {
      int d;
      while (In >> d) num++; // count values from file
      In.close();            
      data = new int[num]; // create dynamic array
      In.open("file.txt");   
      for (int i=0; i < num; i++) // read it to array
	In >> data[i];
      In.close();
    }
  else 
    {
      cout << "could not open file.txt" << endl;
      return 0;
    }

  // Write it out to check if everything is alright!
  for (int i=0; i < num; i++)
    cout << data[i] << endl;
you would need to read the file line by line and then check if the value is an integer.
if it is put it in your array
if else discard and it and go to the next line.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
	// storage for your data
	vector<int> data;
  ifstream In("file.txt"); 
  if (In.good()) 
    {      
		string line;
	  while (getline(In,line)) // while it is still not the end of file
	  {
		  std::cout << line << std::endl;
		  
		  // simple check to see if the string size is greater than 4 
		  if(line.size() > 4)
		  {
			// dont do anything if string is greater than 4
		  }
		  else
		  {
			 try
			  {
				  // convert a string to an int
				stringstream  temp;
				temp  << line;
				int data_val;
				temp >> data_val;

				// insert to the end of the vector
				data.push_back(data_val);
			  }
			  catch(exception &e)
			  {
				  // display error
				  std::cout << e.what() << std::endl;
			  }
		  }
		 
	  }
      In.close();            
      
	  cout << endl;

	  // double check you read all your data
      for (auto i: data)
	  {
		  cout << i << endl;
	  }
    }
  else 
    {
      cout << "could not open file.txt" << endl;
      return 0;
    }

  int x;
  cin >> x;
  return 0;
}
Last edited on
Topic archived. No new replies allowed.