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 .
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().
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.
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.
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 ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With