Reading delimited files in C++ [duplicate] - c++

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 8 years ago.
What is the best way to read in a tab delimited file in C++ and store each line as a record? I have been looking for an open source library to help with this, but have been unsuccessful so it looks like I will have to write my own.

typedef vector<vector<string> > Rows;
Rows rows;
ifstream input("filename.csv");
char const row_delim = '\n';
char const field_delim = '\t';
for (string row; getline(input, row, row_delim); ) {
rows.push_back(Rows::value_type());
istringstream ss(row);
for (string field; getline(ss, field, field_delim); ) {
rows.back().push_back(field);
}
}
This will get you started. It doesn't do any checking that each row has the same number of fields, allow for escaping field_delim, etc.

There is no problem in using iostreams - you could read each line with getline into string, and then use stringstream on that string to iterate over fields.

There are a few libraries listed in wikipedia's article CSV_application_support.

Related

trying to give a variable to ifstream in c++ [duplicate]

This question already has answers here:
Put A String In A ifstream Method [duplicate]
(2 answers)
No matching function - ifstream open()
(1 answer)
Closed 3 years ago.
im new to c++ and trying to put a variable in this line : ifstream studentPaper(paper);
ill pass paper to this function and want to use it there. string paper has my files location (/name/file.txt)
if i put my file name there i dont get any errors = ifstream studentPaper("/name/file.txt");
but when i save my files location in to a string and give string to it ill get error = ifstream studentPaper(paper);
how can i do that without getting errors
void matchGrades(string paper) {
string aa= "asd";
ifstream studentPaper(paper);
ifstream base("base.txt");
int grade=3;
while ((!studentPaper.eof()) && (!base.eof())) {
string l1,l2;
getline(studentPaper,l1);
getline(base,l2);
if(l1==l2){
grade += 3;
} else {
grade -= 3;
}
}
studentPaper.close();
base.close();
cout << grade;
I think that You have to use removed string parameter "/name/file.txt" because parameter split space.
Try doing ifstream studentPaper(paper.c_str()).
Also if your file is located where your main.cpp is you won't need to specify the path. Something like this:
string studentFile = "student_file.txt";
Based on the information provided. If you are still getting an error please post it so that I can adjust my answer.

Clear CSV-file from non-specified symbols using C++ [duplicate]

This question already has answers here:
Why can Windows not read beyond the 0x1A (EOF) character but Unix can? [duplicate]
(2 answers)
Closed 3 years ago.
I'm trying to convert CSV-file to TXT-file using simple C++-code like this:
std::ofstream txtFile(strFileName, std::ofstream::out | std::ofstream::app);
std::string strLine;
std::ifstream csvFile(strCSVDir);
while (std::getline(csvFile, strLine))
{
std::string subString;
std::stringstream s(strLine);
while (std::getline(s, subString, ';'))
{
txtFile << subString << "\t";
}
txtFile << "\n";
}
txtFile.close();
csvFile.close();
It works fine, but only if the CSV-file doesn't contain any non-specified symbols, like arrow on this picture:
In this case my code can read only part of CSV-file until it meet this arrow symbol. How can I get around this situation?
Update: if I look at this CSV-file in byte-representation (for example in Far Hex-view), than I see code of arrow-symbol is "1A". The table of Unicode-characters points that it is Substitute symbol. How does it get in this CSV-file I don't know.
It might be easier to just read the entire file - then replacing and finally saving.
Going from your snippet:
std::stringstream sstr;
sstr << csvFile.rdbuf();
std::string buffer = sstr.str();
boost::replace_all(buffer, ";", "");
txtFile << buffer;
Update: if you don't have boost it should be easy to replace with something else like a for loop (since it is just a single char replacement)
Update 2: The reason why reading might not read the entire file in this case is because it is being read as a text file and probably contains a terminating character somewhere due to the way it is being read - see https://en.cppreference.com/w/cpp/io/c#Binary_and_text_modes for explaination.

c++ getline putting different parts of a line into variables [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 5 years ago.
For the life of me, I can't seem to figure out how to do this properly.
First, I read a line from a csv file. Lets say, that line has
2992854,BOB,3452,394832
I don't want to read each result into a console like practically every example I've found, I want them to go in order, into these 4 variables:
int time;
string name;
int location;
int point;
Right now, this is my code:
string line;
ifstream inputFile("input.csv");
std::list<Cramista> Cramistas;
while (!inputFile.eof())
{
int time;
string name;
int location;
int point;
std::vector<std::string> stringArray;
std::size_t position = 0, found;
getline(inputFile, line);
while ((found = line.find_first_of(',', position)) != std::string::npos)
{
stringArray.push_back(line.substr(position, found - position));
position = found + 1;
}
time = stoi(stringArray[0]);
name = stringArray[1];
location = stoi(stringArray[2]);
point = stoi(stringArray[3]);
}
UPDATED:
So, with what I have here, I'm able to get the first 3 out of 4 pieces of the line, and put them into an array, which I can then move into variables. Trying to figure out how to get that 4th part.
I've got 2992854, BOB, and 3452 but I don't have 394832.
I mean basically in order to avoid "reading each result into the console" using
cin >> time >> name >> location >> point;
you would have to split the line by commas (assuming it's a string, then convert the non string data to integers.

"New Line" connected to value when reading in a CSV? [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 6 years ago.
I am currently trying to read in a CSV file to place it into an array, but when I execute the code, the program seems to read over the endline to the next comma which messes up my output. Here is the code:
while (!inFile.eof()) {
string line = "";
while (count_1 <= numValuesPerLine) {
getline(inFile, readFromFile, ',');
line.append(readFromFile);
count_1++;
}
cout << line << endl;
count_1 = 0;
}
'line' ends up having the value:
12345678910111213141516171819202122232425\n1
which when I print it, places that newline next to '25' and messes up the output.
(numValuesPerLine = 25 and count_1 is initialized outside of the loop)
I looked around for a similar answer but I could not find anything exactly like what I am trying to do, any help would be greatly appreciated, thank you.
you changed the delimiter from \n to , so of course the newline is kept as part of the input

How to read a comma delimited text file into arrays [duplicate]

This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
How to use stringstream to separate comma separated strings [duplicate]
(2 answers)
Closed 8 months ago.
I have been working on this project and been reading in text files with ONLY spaces in between and not commas so I need to update how I read in the file into arrays. I have tried using stringstream() and getline() but no luck. Does anyone know how I can read in this file into arrays?
This is how I been doing it before
void readData(ifstream& inputFile, double lat[], double lon[], double yaw[], int& numLines)
{
// Read in headers.
string header;
getline(inputFile, header);
// Read in data and store in arrays.
for (int i = 0; i < numLines; i++)
{
if (inputFile >> lat[i])
{
inputFile >> lon[i];
inputFile >> yaw[i];
}
}
but Im not sure how to modify it to read in this type of file into arrays and also the only ones I'm interested in are
latitude
longitude
altitude(feet)
speed(mph)
gps
power
pitch
roll
yaw
motor on
834,,,,,,,,,,,,,,,,
latitude,longitude,altitude(feet),ascent(feet),speed(mph),distance(feet),max_altitude(feet),max_ascent(feet),max_speed(mph),max_distance(feet),time(millisecond),gps,power,pitch,roll,yaw,motor on
43.5803481,-116.7406331,0,0,0,0,0,0,0,0,539,10,97,178,180,141,0
43.5803481,-116.7406329,0,0,0,0,0,0,0,0,841,10,97,178,180,141,0
43.5803482,-116.7406328,0,0,0,0,0,0,0,0,1125,10,97,178,180,141,0
43.5803481,-116.7406329,-1,0,0,0,0,0,0,0,1420,10,97,178,180,141,0
43.580348,-116.7406328,0,0,0,0,0,0,0,0,1720,10,97,178,180,140,0
43.5803479,-116.7406326,-1,0,0,0,0,0,0,0,2023,10,97,178,180,140,0
43.5803478,-116.7406326,0,0,0,0,0,0,0,0,2344,10,97,178,180,140,0
43.5803476,-116.7406329,-1,0,0,0,0,0,0,0,2620,10,97,178,180,140,0
43.5803475,-116.7406329,-1,0,0,0,0,0,0,0,2922,10,97,178,180,140,0
43.5803473,-116.7406329,0,0,0,0,0,0,0,0,3221,10,97,178,180,140,0
If someone can point in the right direction that would be great. Thanks
You need to extract those commas, to the variable of type char:
std::ifstream f("d:\\temp\\z.txt");
string s;
double lat, lon, alt, asc, speed, dist, max;
vector<double> lat_vec, lon_vec, asc_vec, speed_vec, dist_vec, max_vec;
char c;
while (!f.eof()) {
f>>s; // get one line
stringstream st(s);
// below, eat first number, then comma, then second number, etc.
if (st>>lat>>c>>lon>>c>>alt>>c>>asc>>c>>speed>>c>>dist>>c>>max) {
lat_vec.push_back(lat); lon_vec.push_back(lon);
asc_vec.push_back(asc); speed_vec.push_back(speed);
dist_vec.push_back(dist); max_vec.push_back(max);
}
}
// if you really need arrays, not vectors
double *dist_ar = new double[dist_vec.size];
for (int i=0;i<dist_vec.size(); i++)
dist_ar[i]=dist_vec[i];
return 0;