getLine() returns newline and no data - c++

I have the following code:
const char *fn = fileName.c_str();
std::ifstream file (fn);
std::vector<std::string> value(20000);
int i = 0;
while ( file.good() )
{
getline ( file, value[i] );
i+=1;
std::cout << value[i]<< std::endl;
std::cout << i << std::endl;
}
The program reads the whole file, I know this because the correct number of indexes are printed. However there is no data, just a new line before each printing of "i". This is a file that I have saved from excel in windows and am reading in Linux - Is this my issue? What happened to my data?

there is no data, just a new line before each printing of "i".
Because you increment i before accessing value[i].
Incrementing i just after accessing value[i] solves the problem of missing data.
DEMO

A better way to read in the file:
std::string text_line;
std::vector<string> file_lines;
while (std::getline(file, text_line))
{
file_lines.push_back(text_line);
}
Although not optimal speed-wise, it gets the job done and doesn't have an upper limit (except by the amount of memory your program is allowed).

Edit:
Sorry, I was simply fixing the logic error apparent.
However, here is an ideal version of reading lines of a file:
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::ifstream file {"test.txt"};
std::vector<std::string> values;
std::string temp;
while (getline(file, temp)) {
values.push_back(temp);
}
for (int i = 0; i < values.size(); ++i) {
std::cout << values[i] << '\n' << i << '\n';
}
}

Related

getline causing a segmentaion fault in C++?

I am currently trying to learn C++. I am given a .txt file that contains a different individuals data on each line. I want to read that data into an array of strings. I don't see anything wrong with this function and I have done the same thing before, but for some reason I am receiving a segmentation fault.
#include <string>
#include <iostream>
#include <fstream>
void readFile(std::istream&, std::string*);
int lineCount(std::istream&);
int main(){
std::ifstream inFile("input.txt");
int numLines = lineCount(inFile);
std::string data[numLines];
inFile.close();
inFile.open("input.txt");
readFile(inFile, data);
inFile.close();
return 0;
}
int lineCount(std::istream& inFile){
std::string line;
int numLines = 0;
while(std::getline(inFile, line)){
numLines++;
}
return numLines;
}
void readFile(std::istream& inFile, std::string *data){
int i = 0;
while(std::getline(inFile, data[i])){
std::cout << i << "\n"; //testing values
std::cout << data[i] << "\n"; //testing values
i++;
}
}
Here is the output of the above code.
//Output
//Note, these are fictional people
0
Florence,Forrest,1843 Glenview Drive,,Corpus Christi,TX,78401,10/12/1992,5/14/2012,3.215,127/11/1234,2.5,50
1
Casey,Roberta,3668 Thunder Road,,Palo Alto,CA,94306,2/13/1983,5/14/2014,2.978,95
2
Koch,Sandra,2707 Waterview Lane,Apt 302,Las Vegas,NM,87701,6/6/1972,12/14/2015,2.546,69
Segmentation fault //occurs in while condition
Any help would be appreciated
I feel sick that I didn't see this right away.
int numLines = lineCount(inFile);
returns the correct number of lines in the file. Bug's not here, man.
std::string data[numLines];
Is not kosher C++, but will create an array with an element for every line in the file if supported. Your program is running, so it's supported. Still, prefer to use Library Containers.
Meanwhile in readFile...
while(std::getline(inFile, data[i]))
Will try to read a line into data[i]. Whether the read succeeds or not, there must be a data[i] to read into. There won't be for the last try.
The logic goes
read in line 1. Successful, so
read in line 2. Successful, so
read in line 3. Successful, so
read in line 4. Fail. But this does not keep getline from looking off the end of data for a string and going boom (specifically undefined behaviour that manifested as going boom) because there isn't one.
The right solution
int main(){
std::ifstream inFile("input.txt");
// no longer need. Vector keeps track for us
// int numLines = lineCount(inFile);
std::vector<std::string> data;
// read nothing from file. Don't need to rewind
readFile(inFile, data);
// note: files close themselves when they are destroyed.
//inFile.close();
return 0;
}
void readFile(std::istream& inFile, std::vector<std::string> & data){
int i = 0;
std::string line; // line to read into. Always there, so we don't have to worry.
while(std::getline(inFile, line)){
std::cout << i << "\n"; //testing values
std::cout << line << "\n"; //testing values
data.push_back(line); // stuff line into vector.
i++;
}
}
The No vector Allowed Solution
int main(){
std::ifstream inFile("input.txt");
int numLines = lineCount(inFile);
// legal in every C++, but prefer container may want some extra armour
// here to protect from numlines 0.
std::string * data = new std::string[numlines];
// the following is a faster way to rewind a file than closing and re-opening
inFile.clear(); // clear the EOF flag
inFile.seekg(0, ios::beg); // rewind file.
readFile(inFile, data);
inFile.close();
return 0;
}
void readFile(std::istream& inFile, std::string * data){
int i = 0;
std::string line; // same as above. line is here even if data[i] isn't
while(std::getline(inFile, line)){
std::cout << i << "\n"; //testing values
std::cout << line << "\n"; //testing values
data[i] = line; // stuff line into array. Smart compiler may realize it can move
//if not, c++11 adds a formal std::move to force it.
i++;
}
}

How to read a file, reverse part of the text and write that reversed part on another file on C++?

I need help, I wrote the code, did the reverse thing but I can't get it written on another file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream par2("C:/fajllat/f1.bin", ios::in);
string line;
for (int i = 1; !par2.eof() ; i++)
{
getline(par2, line);
if (i < 5 || i >14) continue;
line = string(line.rbegin(), line.rend());
}
par2.close();
ofstream mbrapsht ("C:/fajllat/f3.bin", ios::out);
mbrapsht << line;
mbrapsht.close();
cin.get();cin.get();
return 0;
}
When I check the files the f3.bin file is empty
You have the right idea. What you're missing is that if you want to write the reversed lines, you need to either write them inside the loop or store them for after. You are doing neither of these things.
Currently what happens is you overwrite line every loop. And whatever is left in that string is what you write afterwards. Turns out that for your case, that's an empty string.
Let's make minimal changes to what you have:
// (*) Open the output file before looping
ofstream mbrapsht("C:/fajllat/f3.bin", ios::out);
for (int i = 1; !par2.eof() ; i++)
{
getline(par2, line);
if (i < 5 || i > 14) continue;
line = string(line.rbegin(), line.rend());
// (*) output the line - you also probably want an end-of-line
mbrapsht << line << std::endl;
}
Now, it's okay-ish. But it does have a problem where if getline fails, your code still runs the loop body one more time. This happens if getline hits the end of file (or some other error state), which your loop doesn't pick up until the next iteration (or possibly never, if the error is not EOF).
So, a somewhat better choice might be:
for(int lineNo = 1; std::getline(par2, line); ++lineNo)
{
if (lineNo >= 5 && lineNo <= 14)
{
std::reverse(line.begin(), line.end()); // (*) requires <algorithm>
mbrapsht << line << std::endl;
}
}
Note that I also inverted your test condition and removed the continue. In general, I avoid continue and break in loops unless not using them results in code that is hard to follow or understand at a glance. It's a style/maintainability thing. Take it or leave it.
See this snippet . For line-by-line reversal, you can use getline() instead and reverse before pushing into vector<string>.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
ifstream par2("D:\\MyFolder\\try.txt", ios::in);
if (par2.is_open())
{
stringstream strStream;
strStream << par2.rdbuf();
str = strStream.str();
cout << str << endl;
par2.close();
}
cout << "\n\nReversing ...\n\n";
std::reverse(str.begin(), str.end());
cout << str << endl;
ofstream mbrapsht("D:\\MyFolder\\try2.txt", ios::out);
mbrapsht << str;
mbrapsht.close();
return 0;
}
Output:

C++ Read in a file like a grid

I'm coding in C++ and I'm trying to read in a file that I'd like to access certain chars at later. As in, what is the char at (line x, char y), at any given point in the file.
My only thought right now is to look for a newline character, and somehow index them so that I can refer back to newline x, check the length of a line, and pull a char at whatever position given the line length.
I'm not sure if that is a good approach or not.
Try this (for character in line "lineNum" and column "columnNum"):
ifstream inf;
inf.open(filename); //filename being c-string
string str;
for (int i = 0; i < lineNum; i++)
{
std::getline(inf, str);
}
This way "str" stores the line you are interested in (automatically checks for newline character and stops).
Then you can use:
char chr = str[columnNum];
to store the character you want in "chr" variable. And don't forget:
inf.close();
Unfortunately, to my knowledge you need to repeat this process every time you want to access a character.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#define FILENAME "File.txt"
class FileGrid {
public:
typedef std::vector<std::string> Line;
typedef std::vector<std::string>::const_iterator LineIter;
typedef std::vector<std::vector<std::string>> StringMap;
typedef std::vector<std::vector<std::string>>::const_iterator StringMapIter;
void FillGrid(char* fileName) {
grid.clear();
std::ifstream in(FILENAME, std::ifstream::in);
if (!in.is_open()) {
std::cout << "problem reading " << FILENAME << std::endl;
return;
}
std::string words;
std::string word;
std::stringbuf buffer;
while (in.is_open() && std::getline(in, words)) {
std::stringstream ss(words);
Line line;
while (ss >> word) {
line.push_back(word);
}
grid.push_back(line);
}
}
void PrintGrid() {
StringMapIter b = grid.begin();
StringMapIter e = grid.end();
std::cout << "\t\tFile Content:" << std::endl;
while(b != e) {
for (unsigned int i = 0; i < b->size(); ++i) {
std::cout << b->operator[](i) << " ";
}
std::cout << std::endl;
++b;
}
}
char const & GetChar(int lineNo, int charNo) {
// LineNo checks etc
Line const & line = grid[lineNo];
for(std::string const & word : line ) {
if(charNo > word.size() + 1) {
charNo -= word.size() + 1;
}
else {
return word[charNo];
}
}
throw std::exception("charNo higher");
}
private:
StringMap grid;
};
void main() {
FileGrid grid;
grid.FillGrid(FILENAME);
grid.PrintGrid();
std::cout << grid.GetChar(0, 3); // should return first line, 4th character
}
Not the best code I've ever written but pretty much what I could do in a short time.
FileGrid handles reading and accessing the data. It reads the file line by line and stores it in a std::vector. When it finishes reading a line, it pushes that into another std::vector. In the end, we have a (sort of) 2D array of strings.
Again, not the best code and definitely not the most optimized code but the idea is still the same: read from the file line by line, separate each word and put them into an array of strings. If you can't use STL, you can dynamically create a 2D array for each line but since I don't know the specific requirements of your question, I just wrote something simple and bruteforce to show you the main way of storing grid of strings into the memory.
As long as it works. But reading the entire file into memory, if that's an option, would be simpler.

c++ program for reading an unknown size csv file (filled only with floats) with constant (but unknown) number of columns into an array

was wondering if someone could give me a hand im trying to build a program that reads in a big data block of floats with unknown size from a csv file. I already wrote this in MATLAB but want to compile and distribute this so moving to c++.
Im just learning and trying to read in this to start
7,5,1989
2,4,2312
from a text file.
code so far.
// Read in CSV
//
// Alex Byasse
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textread.csv", "r");
int ch;
int c = 0;
bool tmp = true;
while (EOF != (ch=getc(infile))){
if(',' == ch){
++c;
}
if ('\n' == ch){
if (tmp){
int X = c;
tmp = false;
}
++number_of_lines;
}
}
fclose(infile);
std::ifstream file( "textread.csv" );
if(!file){
std:cerr << "Failed to open File\n";
return 1;
}
const int ROWS = X;
const int COLS = number_of_lines;
const int BUFFSIZE = 100;
int array[ROWS][COLS];
char buff[BUFFSIZE];
std::string line;
int col = 0;
int row = 0;
while( std::getline( file, line ) )
{
std::istringstream iss( line );
std::string result;
while( std::getline( iss, result, ',' ) )
{
array[row][col] = atoi( result.c_str() );
std::cout << result << std::endl;
std::cout << "column " << col << std::endl;
std::cout << "row " << row << std::endl;
col = col+1;
if (col == COLS){
std:cerr << "Went over number of columns " << COLS;
}
}
row = row+1;
if (row == ROWS){
std::cerr << "Went over length of ROWS " << ROWS;
}
col = 0;
}
return 0;
}
My matlab code i use is >>
fid = fopen(twoDM,'r');
s = textscan(fid,'%s','Delimiter','\n');
s = s{1};
s_e3t = s(strncmp('E3T',s,3));
s_e4q = s(strncmp('E4Q',s,3));
s_nd = s(strncmp('ND',s,2));
[~,cell_num_t,node1_t,node2_t,node3_t,mat] = strread([s_e3t{:}],'%s %u %u %u %u %u');
node4_t = node1_t;
e3t = [node1_t,node2_t,node3_t,node4_t];
[~,cell_num_q,node1_q,node2_q,node3_q,node_4_q,~] = strread([s_e4q{:}],'%s %u %u %u %u %u %u');
e4q = [node1_q,node2_q,node3_q,node_4_q];
[~,~,node_X,node_Y,~] = strread([s_nd{:}],'%s %u %f %f %f');
cell_id = [cell_num_t;cell_num_q];
[~,i] = sort(cell_id,1,'ascend');
cell_node = [e3t;e4q];
cell_node = cell_node(i,:);
Any help appreciated.
Alex
I would, obviously, just use IOStreams. Reading a homogeneous array or arrays from a CSV file without having to bother with any quoting is fairly trivial:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::istream& comma(std::istream& in)
{
if ((in >> std::ws).peek() != std::char_traits<char>::to_int_type(',')) {
in.setstate(std::ios_base::failbit);
}
return in.ignore();
}
int main()
{
std::vector<std::vector<double>> values;
std::istringstream in;
for (std::string line; std::getline(std::cin, line); )
{
in.clear();
in.str(line);
std::vector<double> tmp;
for (double value; in >> value; in >> comma) {
tmp.push_back(value);
}
values.push_back(tmp);
}
for (auto const& vec: values) {
for (auto val: vec) {
std::cout << val << ", ";
}
std::cout << "\n";
}
}
Given the simple structure of the file, the logic can actually be simplified: Instead of reading the values individually, each line can be viewed as a sequence of values if the separators are read automatically. Since a comma won't be read automatically, the commas are replaced by spaced before creating the string stream for the internal lines. The corresponding code becomes
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<double> > values;
std::ifstream fin("textread.csv");
for (std::string line; std::getline(fin, line); )
{
std::replace(line.begin(), line.end(), ',', ' ');
std::istringstream in(line);
values.push_back(
std::vector<double>(std::istream_iterator<double>(in),
std::istream_iterator<double>()));
}
for (std::vector<std::vector<double> >::const_iterator
it(values.begin()), end(values.end()); it != end; ++it) {
std::copy(it->begin(), it->end(),
std::ostream_iterator<double>(std::cout, ", "));
std::cout << "\n";
}
}
Here is what happens:
The destination values is defined as a vector of vectors of double. There isn't anything guaranteeing that the different rows are the same size but this is trivial to check once the file is read.
An std::ifstream is defined and initialized with the file. It may be worth checking the file after construction to see if it could be opened for reading (if (!fin) { std::cout << "failed to open...\n";).
The file is processed one line at a time. The lines are simply read using std::getline() to read them into a std::string. When std::getline() fails it couldn't read another line and the conversion ends.
Once the line is read, all commas are replaced by spaces.
From the thus modified line a string stream for reading the line is constructed. The original code reused a std::istringstream which was declared outside the loop to save the cost of constructing the stream all the time. Since the stream goes bad when the lines is completed, it first needed to be in.clear()ed before its content was set with in.str(line).
The individual values are iterated using an std::istream_iterator<double> which just read a value from the stream it is constructed with. The iterator given in is the start of the sequence and the default constructed iterator is the end of the sequence.
The sequence of values produced by the iterators is used to immediately construct a temporary std::vector<double> representing a row.
The temporary vector is pushed to the end of the target array.
Everything after that is simply printing the content of the produced matrix using C++11 features (range-based for and variables with automatically deduced type).
As proposed here changing getline escape may help you with better reading of csv file but you need to change type from string to int.
For dealing with any number of rows and cols you may use multi dimensional vector (vector inside vector as described here), then you have each row in one vector and all rows in the bigger vectors
int fclose(infile);
This line is wrong. The compiler thinks you're trying to initialize the variable fclose with a FILE*, which is wrong. It should be this if you're simply trying to close the file:
fclose(infile);
I intended this as an edit to Dietmar Kuhl's solution, but it was rejected as too large an edit...
The usual reason given for converting Matlab to C++ is performance. So I benchmarked these two solutions. I compiled with G++ 4.7.3 for cygwin with the following options "-Wall -Wextra -std=c++0x -O3 -fwhole-program". I tested on a 32-bit Intel Atom N550.
As input I used 2 10,000 line files. The first file was 10 "0.0" values per line, the second file was 100 "0.0" values per line.
I timed from the command line using time and I used the average of the sum of user+sys over three runs.
I modified the second program to read from std::cin as in the first program.
Finally, I ran the tests again with std::cin.sync_with_stdio(false);
Results (time in seconds):
sync no sync
10/line 100/line 10/line 100/line
prog A 1.839 16.873 0.721 6.228
prog B 1.741 16.098 0.721 5.563
The obvious conclusion is that version B is slightly faster, but more importantly, you should disable syncing with stdio.

How To Parse String File Txt Into Array With C++

I am trying to write a C++ program, but I am not familiar with C++. I have a .txt file, which contains values as follows:
0
0.0146484
0.0292969
0.0439453
0.0585938
0.0732422
0.0878906
What I have done in my C++ code is as follows:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
ifstream myReadFile;
myReadFile.open("Qi.txt");
if(myReadFile.is_open())
{
while(myReadFile.good())
{
getline(myReadFile,line);
cout << line << endl;
}
myReadFile.close();
}
return 0;
}
I would like to make the output of the program an array, i.e.
line[0] = 0
line[1] = 0.0146484
line[2] = 0.0292969
line[3] = 0.0439453
line[4] = 0.0585938
line[5] = 0.0732422
line[6] = 0.0878906
Assuming you want your data stored as floating point numbers (not strings) you probably want to do something like this:
#include <iostream>
#include <vector>
#include <iterator>
#include <fstream>
int main() {
std::ifstream in("Qi.txt");
// initialize the vector from the values in the file:
std::vector<double> lines{ std::istream_iterator<double>(in),
std::istream_iterator<double>() };
// Display the values:
for (int i=0; i<lines.size(); i++)
std::cout << "lines[" << i << "] = " << lines[i] << '\n';
}
Just a quick note on style: I prefer to see variables fully initialized right when you create them, so std::ifstream in("Qi.txt"); is preferable to std::ifstream in; in.open("Qi.txt");. Likewise, it's preferable to initialize the vector of lines directly from istream iterators rather than create an empty vector, then fill it in an explicit loop.
Finally, note that if you insist on writing an explicit loop anyway, you never want to use something like while (somestream.good()) or while (!somestream.eof()) to control your loop -- these are mostly broken, so they don't (dependably) read a file correctly. Depending on the type of data involved, they'll frequently appear to read the last item from the file twice. Usually, you want something like while (file >> value) or while (std::getline(file, somestring)). These check the state of the file immediately after reading, so as soon as reading fails they fall out of the loop, avoiding the problems of the while (good()) style.
Oh, as a side note: this is written expecting a compiler that (at lest sort of) conforms with C++11. For an older compiler you'd want to change this:
// initialize the vector from the values in the file:
std::vector<double> lines{ std::istream_iterator<double>(in),
std::istream_iterator<double>() };
...to something like this:
// initialize the vector from the values in the file:
std::vector<double> lines(( std::istream_iterator<double>(in)),
std::istream_iterator<double>() );
First you'll need a vector:
std::vector<std::string> lines; // requires #include <vector>
Then you'll need to take a string taken from the getline operation, and push it back into the vector. It's very simple:
for (std::string line; std::getline(myReadFile, line);)
{
lines.push_back(line);
}
For an output operation, all you need is:
{
int i = 0;
for (auto a : lines)
{
std::cout << "lines[" << i++ << "] = " << a << std::endl;
}
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
ifstream myReadFile;
myReadFile.open("Qi.txt");
if(myReadFile.is_open())
{
for(int i=0;i<7;++i)
if(myReadFile.good())
{
getline(myReadFile,line);
cout<<"line["<<i<<"] = " << line << endl;
}
myReadFile.close();
}
return 0;
}