Returning the first column of a file and storing it into an array.

I am trying to read the first column of an input file and store in to an array. The file has 7 rows and 13 columns however I am only interested in the first column being stored. This is my code and it only outputs the first line of the input file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 int main()
{
 string Name;
 int i = 0;
 
 ifstream infile("data.txt");
 if (infile.is_open())
  {
   string line;
   getline (infile,line);
   
   while (!infile.eof())
    {
     getline(infile, Name, '\n');
     i += 1;
    }
   }
  cout << "Names: " << Name;

 return 0;
}
Start with this loop.
1
2
3
4
while ( getline (infile,line) ) {
  cout << "Read line=" << line << endl;
  // now get the first word....
}
Hello vaughanthedon,

Please provide the input file that you are using. It is a great help to others so they do not have to guess at what you are using.

On line 6 you you define a file stream and open the file, but how do you know that it is open?

The next line if (infile.is_open()) will always be true until the program ends and the stream is closed. This may work, but your file stream could be open and still not be usable.

What I see more often is:
1
2
3
4
5
6
if (!infile)
{
    std::cout<< "\n    An error message\n";

    return 1;  // <--- Because there is no point in continuing with the program until it is fixed.
}

The 1 or any number greater than (0) zero means that something is wrong.

Lines 10 - 16 are the correct way of using what you have in the while condition, but salem c's example is the best way. This will read a file of any size without knowing how many records are in the file.

Inside the while loop you need to take the line that you have read and get just the name, or first column, from the whole line that was read.

When it comes to the input file. Were you given a file to use? Or did you have to make one up and can you change it?

With out seeing the input file I am not sure what is the best approach for this program.

Andy
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
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
   vector<string> names;
// ifstream infile("data.txt");
   istringstream infile( "alpha 1 2 3 4\n"
                         "beta 10 20 30 40\n"
                         "gamma 100 200 300 400\n" );
                         
   if ( !infile )
   {
      cout << "Can't open file\n";
      return 1;
   }

   string line, nm;
   while( getline( infile, line ) )
   {
      stringstream( line ) >> nm;
      names.push_back( nm );
   }

   for ( string s : names ) cout << s << '\n';
}
alpha
beta
gamma
Last edited on
Thank you all for your help!
Topic archived. No new replies allowed.