Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ , reading file lines by numbers

Tags:

c++

ifstream

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 .

like image 540
kuki Avatar asked Jul 09 '15 15:07

kuki


People also ask

How to read values from a file in C?

Steps To Read A File:Open a file using the function fopen() and store the reference of the file in a FILE pointer. Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread(). File close the file using the function fclose().

How do you read from a specific line in a file in C?

Solution 1 You can use fgets [^] in a loop to read a file line by line. When no more lines can be read, it will return NULL. On the first line you can use sscanf[^] to extract the integer.

How do you delete a specific line in a file in C?

Step 1 − Read file path and line number to remove at runtime. Step 2 − Open file in read mode and store in source file. Step 3 − Create and open a temporary file in write mode and store its reference in Temporary file. Step 4 − Initialize a count = 1 to track line number.


1 Answers

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 ;
like image 109
marom Avatar answered Sep 27 '22 20:09

marom