473,396 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

vector<string>.clear() now working -- please help

Hello

I have a program that basically inverts the contents of files except
first line.

It compiles fine but gives me core dump on running. If i comment
temp.clear() it runs fine, but i need it to clear the temp vector for
each file.

********************* code *******************
#include <fstream>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

// This program just inverts the tickers.csv files execpt first line
int main(){

string ticker, line;
string input,output;
ifstream Tickers( "tickers.txt", ios::in);
ifstream Input_File;
ofstream Output_File;
vector <string> temp;

while(Tickers>>ticker){
input = "tempdata/" + ticker + ".csv";
output = "tempdata/" + ticker + "1.csv";
Input_File.open( input.c_str(), ios::in);
Output_File.open ( output.c_str(), ios::app);
while ( Input_File >> line ){
temp.push_back(line);
}
Output_File << temp[0] << endl;
for ( unsigned i = ( temp.size() - 1 ); i > 0; i--)
Output_File << temp[i] << endl;
Input_File.close();
Output_File.close();
temp.clear();
}
return 0;
}
***************************************

tickers.txt contains part of file name. tempdata is a subdirectory. i
have the files to be inverted present in tempdata.

thank you in advance.
Jul 19 '05 #1
12 5027
Gaurav wrote:
Hello

I have a program that basically inverts the contents of files except
first line.

It compiles fine but gives me core dump on running. If i comment
temp.clear() it runs fine, but i need it to clear the temp vector for
each file.

********************* code *******************
#include <fstream>
#include <string>
#include <vector>
#include <iostream> #include <algorithm>
using namespace std;

// This program just inverts the tickers.csv files execpt first line
int main(){

string ticker, line;
string input,output;
ifstream Tickers( "tickers.txt", ios::in);
ifstream Input_File;
ofstream Output_File;
vector <string> temp;

while(Tickers>>ticker){
input = "tempdata/" + ticker + ".csv";
output = "tempdata/" + ticker + "1.csv";
Input_File.open( input.c_str(), ios::in);
Output_File.open ( output.c_str(), ios::app); while ( Input_File >> line ){ while ( std::getline(Input_File, line) )
temp.push_back(line);
}
Output_File << temp[0] << endl; for ( unsigned i = ( temp.size() - 1 ); i > 0; i--)
Output_File << temp[i] << endl; std::copy(temp.rbegin(), temp.rend() - 1, std::ostream_iterator(Output_File));
Input_File.close();
Output_File.close();
temp.clear();
}
return 0;
}
***************************************

tickers.txt contains part of file name. tempdata is a subdirectory. i
have the files to be inverted present in tempdata.

thank you in advance.


Other than the getline (in case you have blanks in a line), it looks OK to me...
Of course, I'm not a guru...
Jul 19 '05 #2
On 8 Oct 2003 10:27:40 -0700, ba********@hotmail.com (Gaurav) wrote:
Hello

I have a program that basically inverts the contents of files except
first line.

It compiles fine but gives me core dump on running. If i comment
temp.clear() it runs fine, but i need it to clear the temp vector for
each file.

********************* code *******************
#include <fstream>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

// This program just inverts the tickers.csv files execpt first line
int main(){

string ticker, line;
string input,output;
ifstream Tickers( "tickers.txt", ios::in);
ifstream Input_File;
ofstream Output_File;
vector <string> temp;
You should get out of the habit of declaring your variables at the top
of the functions. There is not need in C++, and it makes code much
less readable. In addition, it means you can't initialize them at
construction.

while(Tickers>>ticker){
input = "tempdata/" + ticker + ".csv";
output = "tempdata/" + ticker + "1.csv";
Input_File.open( input.c_str(), ios::in);
Output_File.open ( output.c_str(), ios::app);
while ( Input_File >> line ){
temp.push_back(line);
}
Shouldn't that be:
while (getline(Input_File, line)){
temp.push_back(line);
}
Output_File << temp[0] << endl;
for ( unsigned i = ( temp.size() - 1 ); i > 0; i--)
Output_File << temp[i] << endl;


Better would be (using the <algorithm> and <iterator> headers):

std::copy(temp.rbegin(), temp.rend(),
std::ostream_iterator<std::string>(Output_File, "\n"));

This also has the benefit of not crashing when temp.size() is 0, which
I suspect is your problem.

Here's the complete program. Notice that it is quite a lot shorter
thanks to declaring the variables only once they are needed:

#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

using namespace std;

// This program just inverts the tickers.csv files execpt first line
int main(){

ifstream Tickers( "tickers.txt", ios::in);
string ticker;

while(Tickers>>ticker){
string input = "tempdata/" + ticker + ".csv";
string output = "tempdata/" + ticker + "1.csv";
ifstream Input_File( input.c_str(), ios::in);
ofstream Output_File( output.c_str(), ios::app);
vector <string> temp;
while ( Input_File >> line ){
temp.push_back(line);
}
std::copy(
temp.rbegin(),
temp.rend(),
std::ostream_iterator<string>(Output_File, "\n")
);
}
return 0;
}

Tom
Jul 19 '05 #3

"tom_usenet" <to********@hotmail.com> wrote in message
news:4c********************************@4ax.com...
int main(){

string ticker, line;
string input,output;
ifstream Tickers( "tickers.txt", ios::in);
ifstream Input_File;
ofstream Output_File;
vector <string> temp;


You should get out of the habit of declaring your variables at the top
of the functions. There is not need in C++, and it makes code much
less readable. In addition, it means you can't initialize them at
construction.


Say what?
Jul 19 '05 #4
On Wed, 8 Oct 2003 15:54:30 -0400, "jeffc" <no****@nowhere.com> wrote:

"tom_usenet" <to********@hotmail.com> wrote in message
news:4c********************************@4ax.com.. .
>int main(){
>
> string ticker, line;
> string input,output;
> ifstream Tickers( "tickers.txt", ios::in);
> ifstream Input_File;
> ofstream Output_File;
> vector <string> temp;


You should get out of the habit of declaring your variables at the top
of the functions. There is not need in C++, and it makes code much
less readable. In addition, it means you can't initialize them at
construction.


Say what?


The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.

Tom
Jul 19 '05 #5

"tom_usenet" <to********@hotmail.com> wrote in message
news:a4********************************@4ax.com...
On Wed, 8 Oct 2003 15:54:30 -0400, "jeffc" <no****@nowhere.com> wrote:

"tom_usenet" <to********@hotmail.com> wrote in message
news:4c********************************@4ax.com.. .
>int main(){
>
> string ticker, line;
> string input,output;
> ifstream Tickers( "tickers.txt", ios::in);
> ifstream Input_File;
> ofstream Output_File;
> vector <string> temp;

You should get out of the habit of declaring your variables at the top
of the functions. There is not need in C++, and it makes code much
less readable. In addition, it means you can't initialize them at
construction.


Say what?


The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.


Yes, but because you can't initialize them at construction isn't one of
them. In fact, I've sometimes used the instantiation of a dummy object as a
trick to get an early entry point into some code when a DLL or something is
loaded (the constructor for the object gives you the entry point, from where
you can write whatever code you want.)
Jul 19 '05 #6
> > >> You should get out of the habit of declaring your variables at the
top
> of the functions. There is not need in C++, and it makes code much
> less readable. In addition, it means you can't initialize them at
> construction.

Say what?
The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.


Yes, but because you can't initialize them at construction isn't one of
them.


It is the major one.

std::string s("hello");

is more "efficient" than

std::string s;
s = "hello";

since that constructor is more "efficient" than creating an empty string
and then use the assigment operator.
In fact, I've sometimes used the instantiation of a dummy object as a
trick to get an early entry point into some code when a DLL or something is loaded (the constructor for the object gives you the entry point, from where you can write whatever code you want.)


So what?
Jonathan
Jul 19 '05 #7
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message news:<IG**********************@weber.videotron.net >...
>> You should get out of the habit of declaring your variables at the top >> of the functions. There is not need in C++, and it makes code much
>> less readable. In addition, it means you can't initialize them at
>> construction.
>
>Say what?

The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.


Yes, but because you can't initialize them at construction isn't one of
them.


It is the major one.

std::string s("hello");

is more "efficient" than

std::string s;
s = "hello";

since that constructor is more "efficient" than creating an empty string
and then use the assigment operator.


Also, you might not know at the top of the function what the initial
value or constructor parameters are going to be.

GJD
Jul 19 '05 #8
Jonathan Mcdougall wrote:
>You should get out of the habit of declaring your variables at the
top
of the functions. There is not need in C++, and it makes code much
>less readable. In addition, it means you can't initialize them at
>construction.

Say what?

The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.


Yes, but because you can't initialize them at construction isn't one of
them.

It is the major one.

std::string s("hello");

is more "efficient" than

std::string s;
s = "hello";

since that constructor is more "efficient" than creating an empty string
and then use the assigment operator.


Not necessarily. Efficiency is up to the compiler. A good compiler
could recognize the assignment following a declaration and combine
the two as an optimization.

[1] std::string s("hello")
The above executes the constructor with the value "hello".

[2] std::string s;
s = "hello"
The above executes the default constructor then calls the assignment
operator. This may be converted to [1] above by the compiler by
an optimization.

By the way, these kinds of optimizations are actually trivial and
waste more development time then they gain in performanace. The
current school of thought is to get the program working correctly
and finished before worrying about optimizations. Who knows,
perhaps these declarations may be eliminated through a design
or requirements optimization.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 19 '05 #9
Jonathan Mcdougall wrote:
>You should get out of the habit of declaring your variables at the
top
of the functions. There is not need in C++, and it makes code much
>less readable. In addition, it means you can't initialize them at
>construction.

Say what?

The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.


Yes, but because you can't initialize them at construction isn't one of
them.

It is the major one.

std::string s("hello");

is more "efficient" than

std::string s;
s = "hello";

since that constructor is more "efficient" than creating an empty string
and then use the assigment operator.


Perhaps. But it is dependent on the implementation of the
class. Putting the declarations, as the was done in the
rewrite, inside a loop could be terribly inefficient. Say,
for example, the assignment operator reuses the old
character buffer if the new string is smaller than that
which is being replaced? In cases where memory is reallocate
each time through the loop you can lose painfully. I've seen
a 17% speed improvement by declaring a class variable that
allocated memory outside of a loop.

You never know what is, or is not efficient unless you
profile the code. Assuming that a certain construct is more
efficient will cause you no end of surprises. Get it right
first and then if you need to tune performance profile.

Jul 19 '05 #10
> >>>>>You should get out of the habit of declaring your variables at the
top
>>of the functions. There is not need in C++, and it makes code much
>>less readable. In addition, it means you can't initialize them at
>>construction.
>
>Say what?

The OPs code was C style, with all the declarations at the top of the
function. This is bad C++ style, for a number of reasons.

Yes, but because you can't initialize them at construction isn't one of
them.

It is the major one.

Perhaps. But it is dependent on the implementation of the
class. Putting the declarations, as the was done in the
rewrite, inside a loop could be terribly inefficient.


<snip>

My point was not that it is always bad to use default
ctors. There are certain circumstances where you just cannot
provide a value or the default contructor does some trivial
operations compared to another one.

And yes, I know that the optimizations are implementation defined and
that 'efficiency is up to the compiler', which is why the two
occurences of 'efficient' in my post were between double-quotes.

"Efficiency" was to be taken in the sense "correct" or "better", not
"faster" or "cheaper".
Jonathan
Jul 19 '05 #11
> By the way, these kinds of optimizations are actually trivial and
waste more development time then they gain in performanace. The
current school of thought is to get the program working correctly
and finished before worrying about optimizations. Who knows,
perhaps these declarations may be eliminated through a design
or requirements optimization.

Well, I say, change the current school then.
You should optimize with pen and paper before you write a single line of
code. Creating "something that works" is not a substitute for making a good
design.

Jul 19 '05 #12


Gandalf wrote:
By the way, these kinds of optimizations are actually trivial and
waste more development time then they gain in performanace. The
current school of thought is to get the program working correctly
and finished before worrying about optimizations. Who knows,
perhaps these declarations may be eliminated through a design
or requirements optimization.

Well, I say, change the current school then.
You should optimize with pen and paper before you write a single line of
code. Creating "something that works" is not a substitute for making a good
design.


Nobody talked about 'design efficiency' in this thread.
But we talked about optimization by fiddeling at the bit level, which
is usually done better by the compiler.

Of course you are right: Using a quick sort instead of a bubble
sort is some sort of 'optimization' one should make. But there
is no point in 'optimizing' bubble sort by making clever C++ hacks.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: misirion | last post by:
Ciao, vorrei poter scrivere e leggere su files binari dei vettori di stringhe, ed avrei implementato questo codice: ifstream fin(conf.c_str(),ios::binary); char inc; fin.read( inc,...
2
by: ehui928 | last post by:
hi, everybody I am a newbie in STL. When I compile the following program under gcc4.0, I got a the following errors. I wonder whether the form of list< vector<string> > is correct in STL ? //...
5
by: Minkoo Seo | last post by:
Hi list. I'd like to print a line "" given a vector<string> containing "A", "BC", "D", "EF". The following code is what I've written for this purpose: #include <iostream> #include <vector>
10
by: Shafik | last post by:
Hello, I am new to C++. I know the reason is probably template instantiation problems ... but what's the *real* reason I cannot declare a: vector<stringv = vector<string>(4); Thanks!...
5
by: Etrex | last post by:
Hello, This is my first attempt at a c++ program, and it is a long post, please bear with me. I'm trying to read in a text file containing a firewall log, make the information...
6
by: arnuld | last post by:
This works fine, I welcome any views/advices/coding-practices :) /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a program to store each line from a file into a *...
6
by: Mr. K.V.B.L. | last post by:
I want to start a map with keys but an empty vector<string>. Not sure what the syntax is here. Something like: map<string, vector<string MapVector; MapVector.insert(make_pair("string1",...
42
by: barcaroller | last post by:
In the boost::program_options tutorial, the author included the following code: cout << "Input files are: " << vm.as< vector<string() << "\n"; Basically, he is trying to print a vector...
9
by: barcaroller | last post by:
1. If I pass pointers (char*) as iterators to an STL algorithm and the return value is an iterator, can I convert that iterator to a pointer? If yes, how? 2. What is the internal...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.