C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

C++ Source Code


You're Browsing As A Guest! Register Now...
Become a C++ Expert!

Join 358,291 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,473 people online right now.Registration is fast and FREE... Join Now!




C++ read line from file with comma-separated values

This function reads a line from a comma-separated values (CSV) file. Parses each entry into a string, long int, or double and stores each in a separate vector. Also stores information on the order of the entries so the original line can be reconstructed, or so particular elements can be extracted.

Submitted By: jjhaag
Actions:
Rating:
Views: 31,930

Language: C++

Last Modified: October 9, 2007
Instructions: Copy and paste into file. Detailed description and usage are given in the comments. Requires string, fstream, and vector headers.

Snippet


  1. #include <string>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. /******************************************************************************/
  6. /* void readCSV()
  7. *
  8. * Function to read a line from a comma-separated value text file and interpret
  9. * the entries.  Assumes that there are three potential data types - string,
  10. * long/integer, and double/float.  The entries are stored in separate vectors
  11. * that are passed to the function by reference.
  12. *
  13. * Arguments:
  14. *
  15. *                 fstream& infile                -file stream from which to read.  must already be
  16. *                                                         open with read access
  17. *
  18. * vector<string>& stringArray        -vector of strings in which to store the strings
  19. *                                                         that are found in the line
  20. *
  21. * vector<double>& doubleArray        -vector of doubles in which to store the doubles
  22. *                                                         or floats that are found in the line
  23. *
  24. * vector<long>& longArray        -vector of longs in which to store the longs or ints
  25. *                                                         that are found in the line
  26. *
  27. * vector<long>& order                -vector of longs in which to store the ordering of
  28. *                                                         elements in the original line.  0=long, 1=double,
  29. *                                                         2=string.
  30. *
  31. * The ordering of the original elements can be reconstructed and outputted
  32. * using:
  33. *
  34. *         vector<string>::iterator striter=stringArray.begin();
  35.         vector<double>::iterator dbliter=doubleArray.begin();
  36.         vector<long>::iterator longiter=longArray.begin();
  37.         for (long i=0; i<order.size(); ++i) {
  38.                 if (order.at(i)==0) {
  39.                         cout << *longiter << endl;
  40.                         longiter++;
  41.                 } else if (order.at(i)==1) {
  42.                         cout << *dbliter << endl;
  43.                         dbliter++;
  44.                 } else if (order.at(i)==2) {
  45.                         cout << *striter << endl;
  46.                         striter++;
  47.                 }
  48.         }
  49. *
  50. * The function stores entries in the line from the CSV file based their data
  51. * type, which is decided with a few simple rules:
  52. *
  53. * If an entry contains only numerical characters, it is considered to be an
  54. * integer (stored as long integers).  Floating point numbers (stored as
  55. * doubles) must consist entirely of numerical characters, except for a single
  56. * period located anywhere within the entry.  Any entry containing more than one
  57. * period, or any other non-numerical characters, is stored as a string (sorry,
  58. * no support for hex numbers).
  59. *
  60. * Dependencies:  requires the string, vector, and fstream standard C++ headers.
  61. */
  62.  
  63. void readCSV(std::fstream& infile,
  64.                 std::vector<std::string>& stringArray,
  65.                 std::vector<double>& doubleArray,
  66.                 std::vector<long>& longArray,
  67.                 std::vector<long>& order) {
  68.        
  69.         //        declare string buffer
  70.         std::string buffer;
  71.        
  72.         //        get line from file
  73.         getline(infile, buffer, '\n');
  74.        
  75.         //        read through buffer searching for commas or end of string. the start of
  76.         //        each entry is the first element of the string (first word), or the
  77.         //        position after the last comma encountered (all other words).  the end
  78.         //        of the entry is the last element of the string (last word), or the
  79.         //        position before the next comma (all other words)
  80.         std::string temp;
  81.         unsigned long start=0;
  82.         unsigned long end=0;
  83.         while (end<=buffer.size()) {
  84.                
  85.                 //        increment end counter
  86.                 end++;
  87.                
  88.                 //        check if position of 'end' in the string a comma, past the end of
  89.                 //        the string, or just another character.  if at a non-comma character,
  90.                 //        skip to the start of the next loop
  91.                 if (end<buffer.size() && buffer[end]!=',') {
  92.                         continue;
  93.                 }
  94.                
  95.                 //        assign comma-free token to a temporary string
  96.                 temp.assign(buffer,start,end-start);
  97.                
  98.                
  99.                 //        run through each character of the token to determine if it is a
  100.                 //        string, floating-point, or integer, based on number of periods and
  101.                 //        presence of non-numeric characters
  102.                 int containsPeriod=0;
  103.                 int containsAlpha=0;
  104.                
  105.                 for (long i=0; i<(long)temp.size(); ++i) {
  106.                         if (temp[i]=='.') {
  107.                                 //        token contains a '.' character - either a string or a floating point
  108.                                 containsPeriod++;
  109.                         } else if ( temp[i]<48 || 57<temp[i] ) {
  110.                                 //        token contains non-numeric characters - string (sorry no hex)
  111.                                 containsAlpha++;
  112.                         }
  113.                 }
  114.                
  115.                
  116.                 //        based on alphabetical/numerical content and the presence of period/
  117.                 //        decimals, determine whether the entry is an integer, floating-point
  118.                 //        number, or a string
  119.                 if (containsAlpha==0 && containsPeriod==0) {
  120.                         longArray.push_back(atoi(temp.c_str()));
  121.                         order.push_back(0);
  122.                        
  123.                 } else if (containsPeriod==1 && containsAlpha==0) {
  124.                         doubleArray.push_back(atof(temp.c_str()));
  125.                         order.push_back(1);
  126.                 } else {
  127.                         stringArray.push_back(temp);
  128.                         order.push_back(2);
  129.                 }
  130.  
  131.                
  132.                 //        set the start and end to the proper next position
  133.                 end++;
  134.                 start=end;
  135.         }
  136. }

Copy & Paste


Comments

C++21 2008-09-21 10:35:03

Hi, I am a beginner on C++ and I want to implement a C++ program to read CSV files on vectors and matrices so I can manipulate. I copied and pasted the above code but I received the following error in my VC++ 6.0 compěler: --------------------Configuration: ReadingTextFiles_2 - Win32 Debug-------------------- Compiling... ReadingTextFile_2_Main.cpp C:\CONFIN DEL MUNDO\FINANCE\Software\MySoftware\C++\DifferentExamples\Arrays\ReadingTextFiles_2\ReadingTextFile_2_Main.cpp(81) : error C2065: 'getline' : undeclared identifier Error executing cl.exe. ReadingTextFile_2_Main.obj - 1 error(s), 0 warning(s) could you help me to fix my error. Thanks. my email is jhleonjy@yahoo.es


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month