ifstream, best way to ignore part of each line

I'm currently dealing with file data that looks something like this:
1
2
3
4
5
//list.txt
w         56
x         38
y         98
z         22 33 44 55

Each line has a name on the left, and a number on the right.

I already know the order that the file is in, so what I am trying to do is just read the second (right) piece of information in each line.

Here's what I have:

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
#include <iostream>
#include <fstream>

int main()
{
    std::ifstream f("list.txt");
    
    int a;
    int b;
    int c;
    int arr[4];
    
    std::string unnecessary;
    
    f >> unnecessary;
    f >> a;
    
    f >> unnecessary;
    f >> b;
    
    f >> unnecessary;
    f >> c;
    
    f >> unnecessary;
    for (int i = 0; i < 4; i++)
        f >> arr[i];
    
    {
    using namespace std;
    cout << a << endl
         << b << endl
         << c << endl
         << arr[0] << " "
         << arr[1] << " "
         << arr[2] << " "
         << arr[3] << endl;
    }
    
    return 0;
}

Notice the "unnecessary" string that I have. I do this for each line so that it "skips" over that part and then can read the number.
Is there an easier way to do this, something to make it so it automatically only reads the second clump of information on each line? It might not seem like a big deal right now, but for this big file header stuff I'm working with, it makes it really tedious.
Last edited on
No, there really isn't an easier way to do this. You could use loops though instead of writing a line for each letter.
i was going to suggest ignore(), but substr() and a stringstream is another possibility:
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
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using std::cout;
using std::endl;

int main()
{
    std::ifstream f("list.txt");

    int a;
    
    std::string line;
    
    while (std::getline(f, line))
    {
        std::istringstream ss(line.substr(10));
        while (ss >> a)
            cout << a << ' ';
        cout << endl;
    }    
        
    return 0;
}

Output:
56
38
98
22 33 44 55

Last edited on
Heh, so saving a stream line in a string and then using a stringstream on the string to treat it as a stream again. That could work, I'll try to use it, but if not I guess it isn't too big of a deal. Thanks! (For some of the stuff where it doesn't make sense to put it into an array, I'll just have to use a string called "u" ;] )
Last edited on
Why "u"? I recommend a meaningful variable name so in the future when you look at the code, maybe it'll help you remember what you were trying to do.

Topic archived. No new replies allowed.