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!

Was this post helpful?

Related Posts

  • 04 November

    Pass 2D Array to Function in C++

    Table of ContentsWays to Pass a 2D Array to function in C++Pass a 2D Array to a Function by Passing Its PointerPass an Array to the Function by Decaying the Pointer to the ArrayPass a 2D Array to a Function in C++ Without Size by Passing Its ReferenceConclusion Two-dimensional arrays have rows and columns, storing […]

  • 02 November

    Count Decimal Places in C++

    Table of ContentsAccuracy V/S Precision in Counting Decimal Places in C++ ProgramsHow to Count Decimal Places in C++Example 1: Use String Functions to Find Precise Number of Decimal PlacesExample 2: Count Decimal Places Accurately for a NumberExample 3: Create a Program that divides two numbers and returns their decimal placesExample 4: Find the Number of […]

  • 02 November

    Check if String Is Empty in C++

    Table of ContentsWays to Check if String Is Empty in C++Using Empty() methodUsing the Equality OperatorUsing length() methodUsing size() methodConclusion A String is a combination of characters that can store both alphabets and numbers together. In C, there was no concept of string as a datatype so character arrays were used. In C++, this drawback […]

  • 03 October

    Get Filename from Path in C++

    Table of ContentsGet Filename From Path in C++Using find_last_of and substr methodsUsing TemplatesUsing filesysystem library [ C++ 17 ]Conclusion This article explains the various ways to get filename from path using C++ programs. The examples will also describe ways to remove extensions as well if such needs arise. Get Filename From Path in C++ Finding […]

  • 24 September

    Escape Percent Sign in printf Method in C++

    In this post, we will see how to escape percent sign in printf Method in C++. Escape percent sign in Printf Method in C++ printf() method uses percent sign(%) as prefix of format specifier. For example: To use number in prinf() method, we use %d, but what if you actually want to use percent sign […]

  • 15 September

    Remove Last Element from Vector in C++

    Table of ContentsWays to Remove Last Element from Vector in C++Using the vector::pop_back() function to remove last element from vector in C++Using the vector::resize() Function to Remove Last Element from Vector in C++Using the vector::rrase() Function to Remove Last Element from Vector in C++Conclusion Learn about how to remove last element from Vector in C++. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.