-1

I'm a newbie of C++. I'm sorry if my question have any errors.

I have a file with 4 attributes: Name, Position, Birthday, Salary

And i use setw() function to save file.txt with format like this

NAME                POSITION        BIRTHDAY        SALARY
James Smith         CEO             10/12/1991      3000
Robert Wiliam       IT              5/4/1990        4999
Maria Rodriguez     Designer        12/3/1994       4923
Maria Hernandez     Waiter          22/2/1992       4022

Now, i want to read back all of them for each of attribute is each value of this table like this (example for a person):

staff1:
Name: James Smith 
Position: CEO
Birthday: 10/12/1991
Salary: 3000

I have no idea for getting value foreach Staff. Can you give me some ideas?

If each atttribute was saved and separate between them is comma, i'll use

getline(fileIn, name, ',');

but it's not work in this case.

Phi Dinh
  • 1
  • 3
  • Names with spaces like `James Smith` will be problematic. Otherwise you can simply use `ifstream >> data`. –  Jun 25 '19 at 05:45
  • 1
    When you say "it's not work in this case" do you mean because you aren't using commas, or you tried to use commas but it still didn't work? If no commas, does this mean you only intend to separate them by space? – Tas Jun 25 '19 at 05:46
  • Are they perhaps separated by a tab? –  Jun 25 '19 at 05:47
  • 1
    Not as problematic as John Jacob Jingleheimer Schmidt, which will blow the crap out of the output formatting as well as give fits when reading. – user4581301 Jun 25 '19 at 05:47
  • 1
    If you can guarantee the spacing, read 20 characters, then trim off the trailing whitespace. The rest looks like you can read with `>>` – user4581301 Jun 25 '19 at 05:49
  • since setw was used when saving, the number of characters is probably guaranteed – Arne Jun 25 '19 at 05:50
  • @chipster i use setw() to create space to save them – Phi Dinh Jun 25 '19 at 05:54

1 Answers1

2

Use fileIn.getline(name, 20) (assuming 20 spaces set using setw when saving)

Then use
fileIn >> position >> birthday >> salary to read in the rest.

If you don't know if the remaining columns may contain spaces or not, you can continue and use getline instead of the extraction operator.

Arne
  • 1,293
  • 1
  • 7
  • 20