I adapted most of the suggestions from answers for my previous question Printing all the permutations of a string in alphabetical order to rewrote my solution again. Please let me know any more changes required or any more suggestions.
#include <iostream>
#include<fstream>
#include<algorithm>
#include<string>
void create_permute( std::string& record )
{
std::sort( record.begin(), record.end() );
std::cout<<record;
while( std::next_permutation( record.begin(), record.end() ) )
{
std::cout<<","<<record;
}
std::cout << "\n";
}
void readInputFile( std::string filename )
{
std::ifstream infile(filename);
std::string record;
while( std::getline( infile,record ) )
{
create_permute( record );
}
infile.close();
}
int main( int argc, char* argv[] )
{
if( argc < 2 )
{
std::cout << "usage: filesize filename" << "\n";
exit( 0 );
}
std::ios_base::sync_with_stdio( false );
readInputFile( argv[ 1 ] );
return 0;
}
2 Answers 2
Nothing I would bother about complaing about in real code review.
But for argument's sake:
Pass by const ref
Rather than passing by value. It usually means that an extra copy will be removed. In this case that's not true but I think its a good habit.
void readInputFile( std::string const& filename )
No need to return 0 from main
If main()
can not return anything else. Then I don't bother with a return
statement in main
(it's special). The compiler adds a return 0
if no return
is provided for main
.
Personally I use this (that face that I have not added a return) to indicate that the application has no real failure state.
In addition to what has already been said by @Loki Astari, you could add some input parameter check, for example: stream tests/ error handling,
after std::ifstream infile(filename);
in void readInputFile( std::string filename )
to check stream states
and, eventually, recover from: bad()
, fail()
, stream.open()
(not open).
An example would be:
int i=0;
cin>>i;
if(!cin){ // true only if input operation failed
if(cin.bad())error("cin is bad") // stream corrupted (serious problem)
if(cin.eof()){ // no more input
}
if(cin.fail()){ // unexpected input (wrong type/format)
cin.clean() // reset state flags
// use char, error("invalid symbol: ", char) and unget()
// to make clear what is wrong
}
}
Explore related questions
See similar questions with these tags.