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

  • Count lines in file in C++
    01 November

    Count lines in file in C++

    Table of ContentsHow To Count Lines In A File In C++?C++ Program To Count Lines In A FileHow To Count Lines In A File In C++ Using C-style Approach?C++ Program to Count Lines In A File using C-style approachConclusion We often store our data into files when we need the data to be persistent and […]

  • Get Number of Elements in Array in C++
    08 October

    Get Number of Elements in Array in C++

    Table of ContentsGet Number of Elements in Array in C++Using the sizeof() functionUsing the pointersUsing the size() functionGet the frequency of each element in array in C++Using nested for loopUsing maps One of the most fundamental collections in any programming language is an array. It stores a similar type of data at specific indices that […]

  • Trim String in C++
    19 July

    Trim String in C++

    Table of ContentsUsing Boost string algorithms to trim string in C++Using find_first_not_of() and find_last_not_of()` to trim strings in C++Using find_if() to trim the string in C++Using stringstream to trim the strings in C++Using a customized function to trim the strings in C++Conclusion When we take an input from an user, strings can have unwanted whitespaces […]

  • JSON parser in C++
    19 July

    JSON Parser in C++

    Table of ContentsSimple JSON Parser in C++ using JsonCpp libraryConclusion In this post, we will see about JSON parser in C++. There is no native support for JSON in C++. We can use a number of libraries that provide support for JSON in C++. We will use JsonCpp to parse JSON files in C++ which […]

  • Enum to String in C++
    19 July

    Convert enum to string in C++

    Table of ContentsUsing stringify macro method to convert enum to String in C++Using const char* Array to convert enum to String in C++Using a custom-defined function to convert enum to String in C++Conclusion There are a variety of methods to convert enum to String in C++. In this article, we will discuss some of the […]

  • C++ random number between 0 and 1
    11 June

    C++ random number between 0 and 1

    Table of ContentsUsing the rand() function to generate random number between 0 and 1 in C++Using the std::uniform_real_distribution() function to generate random number between 0 and 1 in C++ Random numbers are frequently used in programming for test case generation, cryptography, and other related purposes. In this tutorial, we will generate random number between 0 […]

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.