Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   code in c++ (http://www.go4expert.com/forums/code-in-cpp-t22425/)

reta 15Jun2010 12:45

code in c++
hi to all

I use the following code in c++ under linux, but I need to convert it to c under linux, any one can convert it from c++ to c.

the details of the program is:
It reads a text file and then asks the user to enter a string.
It then displays how many times the string occurs and also prints the lines in which it occurs


using std::istringstream;
using std::ifstream;
using std::string;
using std::cout;
using std::cin;
using std::cerr;
using std::map;
using std::multimap;
int main()
    multimap<string,int> words;
    map<int,string> lines;
    string str;
    ifstream input("test.txt");
        cerr<<"\nThe file could not be opened.";
        return -1;
    int i=1;
        istringstream in(str);
        string s;
    string search;
    cout<<"\nEnter a word to search: ";
    cout<<"\nThe number of matches = "<<words.count(search)<<'\n';
    multimap<string,int>::iterator it1=words.lower_bound(search);
    multimap<string,int>::iterator it2=words.upper_bound(search);
        int x=it1->second;
        map<int,string>::iterator iter=lines.find(x);
        cout<<'\n'<<x<<" ) "<<iter->second<<'\n';
            if(it1!=it2 && it1->second==x)
    return 0;

thanks in advance

xpi0t0s 16Jun2010 14:02

Re: code in c++
You're pretty much going to have to rewrite it from scratch; this code uses a lot of C++ specific syntax all of which is invalid in C. However the C++ code is overcomplicated, you can do it in about quarter the code, and it will be a lot faster as well; just use fgets and strstr (which you could also do in C++, there's no need for this silly multimap stuff and reading the whole file into memory at the start).

print greeting
get string
if fopen
- while !eof
- - get string from file
- - test match with strstr
- - - if it matches add 1 to a count and display the line
- - (handle multiple matches if you need to)
- end while
end if
display the count

If you need to display the count THEN the matching lines, just loop over the file twice; this will be a lot easier than trying to store the matching lines in memory (and will scale to massive files, thus turning that horrendous demonstration of how NOT to write C++ code into a utility that might actually be useful).

All times are GMT +5.5. The time now is 19:26.