Search for string, print line
Mar 15, 2013 at 10:58am UTC
Hi guys
I'm trying to write a code that searches a file for a string from the command line line-by-line and prints each line with the string.
I have this at the moment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream input;
char buffer[200];
bool finished;
string s;
input.open ( argv[1] );
finished = false ;
cout << "LINE2" << endl;
while ( ! finished )
{
input.getline (buffer, 200 );
if ( input.eof () )
finished = true ;
else
cout << buffer << endl;
}
input.close();
input.open ( argv[1] );
finished = false ;
cout << endl << "LINE" << endl;
while ( ! finished )
{
input >> s;
if ( input.eof () )
finished = true ;
else
cout << s << endl;
}
return 0;
}
I'm not sure where to put the location of the text file I want to search, or if that should be defined from the command line?
Also I'm not sure how to run the program successfully, if i type a.out I get nothing and cannot type anything.
What I would like is to be able to compile the code, type the string I want to find ( and file I'm searching??) and run it, and have the program print each line with my string.
Thanks for any help!
Mar 15, 2013 at 11:58am UTC
anyone??
Mar 15, 2013 at 1:11pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using std::cout;
using std::cerr;
using std::string;
using std::endl
//... all of the others
int main(int argc, char *argv[])
{
if (argc != 2)
cerr<<"error: usage: " << argc[0] <<" <file> <expression>" << endl;
else
{
ifstream file;
file.open(argv[1]);
if (!file.good())
cerr<<"error: invalid file: " << argv[1] << endl;
else
{
string line;
while (getline(file, line))
if (strcmp(line.c_str(), argv[2])
cout<< line << endl;
}
}
}
Mar 15, 2013 at 1:34pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
if ( argc != 3 )
{
std::cerr << "Error. Usage: " << argv[0] << " <file> <string>" << std::endl;
std::exit( 1 );
}
ifstream file( argv[1] );
if (!file )
{
std::cerr << "Error. Invalid file name: " << argv[1] << std::endl;
std::exit( 2 );
}
std::string line;
while ( std::getline( file, line ) )
{
if ( line.find( argv[2] ) != std::string::npos )
{
std::cout << line << std::endl;
}
}
return 0;
}
Last edited on Mar 15, 2013 at 1:35pm UTC
Topic archived. No new replies allowed.