how to read a comma delimited file into an array c++
To read a comma delimited file into an array in C++, you can follow these steps:
- Include the necessary header files:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
- Declare a vector to store the data from the file:
std::vector<std::string> dataArray;
- Open the file using an input file stream:
std::ifstream inputFile("filename.csv");
- Check if the file was opened successfully:
if (!inputFile.is_open()) {
std::cout << "Error opening file." << std::endl;
return 1;
}
- Read each line of the file using a while loop:
std::string line;
while (std::getline(inputFile, line)) {
// Process each line here
}
- Split each line into individual values using a delimiter (in this case, a comma):
std::string delimiter = ",";
size_t pos = 0;
std::string token;
while ((pos = line.find(delimiter)) != std::string::npos) {
token = line.substr(0, pos);
dataArray.push_back(token);
line.erase(0, pos + delimiter.length());
}
dataArray.push_back(line); // Add the last token
- Close the input file:
inputFile.close();
Here's the complete code example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> dataArray;
std::ifstream inputFile("filename.csv");
if (!inputFile.is_open()) {
std::cout << "Error opening file." << std::endl;
return 1;
}
std::string line;
while (std::getline(inputFile, line)) {
std::string delimiter = ",";
size_t pos = 0;
std::string token;
while ((pos = line.find(delimiter)) != std::string::npos) {
token = line.substr(0, pos);
dataArray.push_back(token);
line.erase(0, pos + delimiter.length());
}
dataArray.push_back(line); // Add the last token
}
inputFile.close();
// Data is now stored in the dataArray vector
// You can access the elements of the array using the [] operator
return 0;
}
This code reads each line of the file, splits it into individual values using the comma as a delimiter, and stores the values in the dataArray
vector. You can then access the elements of the array using the [ ]
operator.