Store a column results from a text file to another text file as a row

Hi guys.Im having some troubles with reading columns from a text file.
In the first text file i have:

a b c d
1 2 3 4
5 6 7 8
9 10 11 12

The values form each row are sepparated by tabs.
Im trying to make a program that takes a user input represented by the column name(for example "b") and then save all that is under that column in another text file in a row.

For example if the user input is "b" ,the second file should be:

2 6 10

The main issue is that im having problems with reading a text by column,although by row i can make it work.
Thanks.
The main issue is that im having problems with reading a text by column,although by row i can make it work.

One approach is to read the file a whole line at a time. Then get the values from the line.
1
2
3
4
5
6
7
8
9
10
11
12
    fstream fin("data.txt");
    
    fin.ignore(100, '\n'); // skip first line
    
    string line;
    string a, b, c, d;
    while (getline(fin, line))
    {
        istringstream ss(line);
        if (ss >> a >> b >> c >> d)
            cout << b << '\t';
    }


Rather than separate variables a, b, c, d it may be convenient to use an array or perhaps a vector.

http://www.cplusplus.com/reference/sstream/istringstream/

Last edited on
Thank you sir.But still how do i save a column location or something like that?If the user is interogated and inputs "c" it should save 3 7 11
Well, I gave a very simplified version of the code, hoping that it would be easy to understand.

You need extra code, read the first line from the file, (instead of ignoring it as I did), display the header values. Then prompt the user to enter which column they would like. In some ways, it would be easier if the user entered a number rather than a string.

Say the column headings look like this:
rain thunderstorm snow gale

you could output the headings like this
Please choose an option:
  1. rain
  2. thunderstorm 
  3. snow
  4. gale

Then the user enters say '2' instead of typing "thunderstorm"

My reason for heading in this direction is that it makes the next part easier.
Once you have a valid number from the user, you can use it to select the required column of data.

Instead of as I put,
cout << b << '\t';
you might have
cout << array[n-1] << '\t';
where n is the number entered by the user.

array[0] to array[3] would replace the variables a to d that I used before.

Finally, how do you 'save' it - to another file I presume - just replace cout with the name of an ofstream which you have previously opened.
Last edited on
Topic archived. No new replies allowed.