Hi,

I am in need of some help with a small portion of my program.

I have an input file as follows:

10 9 15 program1
11 1 30 important
12 11 10 junk program
14 15 5 other program
17 6 20 another program

I need a function to open the file, read in each line and separate the three integers in the front of the line to separate int variables. I then need to separate the rest of the line into a single string variable. I have not done toom much with file IO in c++ and I am not sure how I can complete this. Here is what I have tried. Thank you for your help in advance. Here is a sample program of what I am talking about.

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    int a,b,c;
    string name;
    ifstream infile;

    infile.open("file.data", ios::in);


    infile >> a >> b >> c >> name;
    cout << a << ' ' << b << ' ' << c << ' ' << name << endl;
    infile >> a >> b >> c >> name;
    cout << a << ' ' << b << ' ' << c << ' ' << name << endl;
    infile >> a >> b >> c >> name;
    cout << a << ' ' << b << ' ' << c << ' ' << name << endl;

    infile.close();

    return 0;
}

Output:

[nnisi@vulcan heap]$ ./a.out
10 9 15 program1
11 1 30 important
12 11 10 junk

The above program works until the third one which has a string with a space in it does not work properly. Does anyonw know how I can change this? Thanks for any and all help!

Nick

Recommended Answers

All 2 Replies

If you have someIstream >> someString it will read up to the first whitespace. Try getline(infile, name) after you get the 3 integers. (I haven't used C++ for a while, so I might be remembering getline wrong; if someone can confirm that I'd appreciate it.)

If you have someIstream >> someString it will read up to the first whitespace. Try getline(infile, name) after you get the 3 integers. (I haven't used C++ for a while, so I might be remembering getline wrong; if someone can confirm that I'd appreciate it.)

I tried it and guess what... IT WORKS! Thanks a lot!

Nick

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.