C++,按数字读取文件行

kuk*_*uki 5 c++ ifstream

我想制作通过数字读取文件的控制台项目.示例:按数字1 2查找,它仅在包含这些数字的文件夹的控制台文本行中打印

   bibi                ceki     1     2
 hasesh              cekiii     1     3
   krki                 cko     1     2
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它只会打印出"bibi ceki"和"krki cko".在我的代码中有许多遗漏的东西.我没有一个循环来检查是否有正确的数字,但这是我能做的最好和我尝试过的:

#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;
}
Run Code Online (Sandbox Code Playgroud)

你可以看到fscanf的行不起作用,我不知道该怎么做.

如果有更好的方法,我需要一些帮助和建议,请尽可能具体,我是c ++/c的新手.

mar*_*rom 6

您正在混合C fscanf函数和C++ ifstream.

我建议使用C++,在这种情况下你可以像这样使用operator >>:

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 ;
Run Code Online (Sandbox Code Playgroud)