How to read CSV file in C++?

Read CSV file in C++

CSV files or Comma Separated Value Files are simple yet special files that we use to store data. Here, each value is separated by a comma, and each line is limited by a newline character. We use CSV files to store tabular data. It helps us in recognizing different column values by separating them by comma and we can recognize the rows by a newline. In this article, we will see how we can read a CSV file in C++. We will discuss ways to read CSV files line by line and then extract the column values from each line. 

What is a CSV File? 

The sample CSV file looks like the one given below.

In this file, each of the values in each line is separated by a comma. The first row represents column names that are name, gender, and age respectively. After each line, there is a newline character that is stored internally and not visible in the file. Each row in the file represents a different record while each comma-separated value represents a field of the record.

How To Read A CSV File In C++?

Reading the CSV file is essentially similar to reading all other files in C++. The difference lies in the way the values are extracted from the lines. To read a CSV file,

  • We will open the file using ‘fstream’ or ‘ifstream’ C++ library. Then, we will read the file line by line using the getline() method as each line ends with a newline character.
  • The getline() method takes a file stream as its first input argument and a string variable as its second argument. After execution, it stores the next line of the file stream in the string variable. It also accepts an optional argument delimitor. If we pass a delimiter as the input argument, it reads the file till the delimiter is found. Otherwise, it reads the file till the newline character is found.
  • After extracting a line, we will use stringstream to extract the words that are separated in the line by a comma. As the name suggests, stringstream converts a string to a file stream-like object. 
  • Here, we will use the getline() method to read the string stream object created by stringstream. While using getline(), apart from the string stream and a string variable named ‘word’, we also pass “,” as the third argument to the getline() function. In this way, the getline() function reads the data only till the next comma sign in a single line.
  • We store each word in a vector named row and Each row is stored in a 2-D vector named content. After execution of the entire program, we get a 2-d vector where each row represents a record in the CSV file and each column of each row represents the data in it.

C++ Code To Read A CSV File

Using the approach discussed above, we have implemented the code to read a CSV file in C++.

The output of the above code is given below. We have used the CSV file given above as the input to the program.

How To Read A CSV File Using C-Based Approach?

Reading the CSV file in C is fundamentally similar to reading a CSV file in C++. However, we will use a different approach to read the content and display the file on the console output. The steps are given as follows.

  • First, we will open the file using the fopen() function. The fopen() function accepts the file name as its first argument and read/write mode as its second argument. Here, we will use the read mode to open the file.
  • We will also create a character array to keep the contents of the file. The size of the array can be decided accordingly. 
  • To read the content from the file into the array, we will use the fgets() function. The fgets() function takes a character array as its first argument, the size of the content to be read as the second argument, and the file pointer as its third argument. After execution, it stores the content read from the file into the character array.
  • After storing the content of the file in a character array, we will use the strtok() function to separate the words using comma as the separator. The strtok() function takes the string as its first input argument and the separator as its second input argument.To search for tokens, the first character is utilized as a starting point when the strtok() function is executed for the first time. The function expects a NULL pointer on subsequent calls and it starts from the right of the end of the last token as the new starting location for scanning. After each scan, it return a token i.e. substring between the separators. Once the entire string is scanned, it returns a NULL value.
  • We will read the file line by line using the fgets() function and will tokenize each comma-separated value using the strtok() function as shown below.

Output:

In the above code, when the strtok() function is executed for the first time, it returns the string till the first comma. On each subsequent execution, it returns the string till the next comma.

Conclusion

Comma Separated Value (CSV) files are used to store tabular data. C++ does not have any inbuilt library to read CSV files directly. However, we can read them like any other file. The files are read line by line and then separated by commas to get each word. In this way, we can read the files in exactly the same way as it is stored in the original spreadsheet or database.

Although C also does not have any built-in library to read the CSV files, we can read the file using file pointers and then read it in the same way as any other file. To get each value, we separate the values by a comma. This is an elegant way to read the values from CSV files which can be used to process the data for further necessities. You can choose any method to read CSV files according to your convenience.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related Posts

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusion This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays and constructors in […]

  • Write String to file in C++
    31 March

    Write String to File in C++

    Table of ContentsUsing the fstream Library to write String to File in C++Using the Insertion Operator (<<) With the fstream ObjectUsing the write() Function of the fstream LibraryUsing the fwrite() Function to write String to File in C++Conclusion The files are used to store the data permanently on a disk. This mitigates the problem of […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusion An array is a […]

  • Print Vector C++
    23 March

    Print Vector in C++

    Table of ContentsPrint Vector in C++ Using IndicesPrint Vector in C++ Using Range-Based for LoopPrint Vector in C++ Using for_each() FunctionPrint Vector in C++ Using IteratorPrint Vector in C++ by Overloading the Insertion Operator (<<)Print Vector in C++ Using copy() FunctionConclusion This article discusses the vector and how to print vector in C++. Vectors are […]

  • Print Map in C++
    15 March

    Print Map in C++

    Table of ContentsMap vs Unordered MapPrint Map in C++ Using IteratorPrint Map in C++ Using Range-Based for LoopPrint Map in C++ by Overloading the ostream Insertion Operator (<<)Print Map in C++17 Using Structure Binding and Range-Based for LoopPrint Map in C++17 Using for_each() FunctionConclusionReferences Maps in C++ store the data in form of key and […]

  • How to write binary files in C++
    14 March

    Write Binary Files in C++

    Table of ContentsOpening a File in Binary Mode Using fstream LibraryWriting the Binary File Using the write() Function of fstream LibraryWriting the Binary File Using the put() Function of fstream LibraryWriting the Binary File Using Insertion Operator (<<) Of fstream LibraryWriting the Structure Object to Binary File Using fstream LibraryConclusion In this post, we will […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.