kuki
kuki

Reputation: 65

C++ , reading file lines by numbers

I want to make console project that reads file by numbers. Example: finding by numbers 1 2 and it only prints in console lines of text from folder that contains those numbers

   bibi                ceki     1     2
 hasesh              cekiii     1     3
   krki                 cko     1     2

In this case it would just print out "bibi ceki" and "krki cko". In my code there are many missing things. I don't have a loop that checks if there are right numbers, but here is best I could do and what I tried :

#include <fstream>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main() {
    char str1[10], str2[10];
    int raz, ode;
    ifstream infile("file.txt");
    while (infile.good()) {
        fscanf(infile, "%s %s %d %d", str1, str2, &raz, &ode); //this thing cant be used lik this 
        while(raz==1 && ode==2) {
            string sLine;
            getline(infile, sLine);
            cout << sLine << endl;
        }
    }
    infile.close();
    return 0;
}

As you can see the line with fscanf is not working and I don't know what to do there .

I need some help and suggestion if there is a better way to do this , and please be specific as much as possible , I'm new in c++/c .

Upvotes: 5

Views: 202

Answers (2)

Andreas DM
Andreas DM

Reputation: 10998

You can read line by line using std::getline until code matches and when it does, you can push_back the names into a std::vector. You can also structure your file with a delimiter, for example '|' so that you read up until that character for names and the rest for codes. Example file would be:

bibi ceki|1 2
hasesh cekiii|1 3
krki cko|1 2

Here is an example of how you could achieve that:

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

using namespace std;

int main()
{
    ifstream in_file("file.txt", ios::in);
    vector<string> vec;
    string names; // store names like: "bibi ceki"
    string codes; // store codes like: "1 2"

    while (getline(in_file, names, '|')) {
        getline(in_file, codes, '\n');
        if (codes == "1 2")
            vec.push_back(names);
    }

    for (unsigned int i = 0; i != vec.size(); ++i)
        cout << vec[i] << endl;

    in_file.close();
}

Output:

bibi ceki
krki cko

Upvotes: 4

marom
marom

Reputation: 5230

You are mixing C fscanf function and C++ ifstream.

I would suggets using C++ and in this case you can use operator>> like this:

std::string str1, str2 ;
...
//substitute the following line with the one below
//fscanf(infile, "%s %s %d %d", str1, str2,&raz,&ode);
infile >> str1 >> str2 >> raz >> ode ;

Upvotes: 6

Related Questions