Editing a certain field on every line in a .csv file

This is a discussion on Editing a certain field on every line in a .csv file within the C++ Programming forums, part of the General Programming Boards category; Lets say I have a .csv (comma separated value) file looking like this: Code: 123,1,"Abc",16.7 124,1,"Def",75.1 125,2,"Ghi",12.2 126,2,"Jkl",78.3 127,3,"Mno",12.3 128,4,"Pqr",84.9 ...

  1. #1
    Pawn, Pascal and C++
    Join Date
    Sep 2005
    Posts
    90

    Editing a certain field on every line in a .csv file

    Lets say I have a .csv (comma separated value) file looking like this:
    Code:
    123,1,"Abc",16.7
    124,1,"Def",75.1
    125,2,"Ghi",12.2
    126,2,"Jkl",78.3
    127,3,"Mno",12.3
    128,4,"Pqr",84.9
    129,4,"Stu",92.0
    I want to find every line which has the number 4 in field 2, and change them to 7.
    That would be these lines:
    Code:
    128,4,"Pqr",84.9
    129,4,"Stu",92.0
    Into this:
    Code:
    128,7,"Pqr",84.9
    129,7,"Stu",92.0
    I was thinking of searching for the first comma on each line, and checking if the number behind it is 4.
    But with my very limited C++ knowledge I don't really know how.
    Could anyone show me how to do this with comments to explain me what you did?

    If anyone is interested, the reason I need this is for mass editing gamedata files that contains thousands of lines,
    instead of opening them up in notepad and editing the lines manually one by one.

    Thanks.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    One way is to use getline and change the delimiter to ',' instead of the default which is a newline '\n'.

    If you call that twice, then you'll get a string holding the second field. Convert that to an int with a stringstream (if necessary) and do your comparison and modification. Output everything as you read it in and just output the modified value for those cases where you are changing it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  2. help again with scrolling without wrapping
    By Dukefrukem in forum C Programming
    Replies: 8
    Last Post: 09-21-2007, 12:48 PM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  5. Trouble replacing line of file
    By Rpog in forum C Programming
    Replies: 4
    Last Post: 04-19-2004, 10:22 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21