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

时间:2015-07-09 15:31:10

标签: c++ ifstream

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

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

在这种情况下,它只会打印出来#b; 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;
}

正如您所看到的,fscanf的行不起作用,我不知道该怎么做。

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

2 个答案:

答案 0 :(得分:6)

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

我建议使用C ++,在这种情况下,您可以使用运算符&gt;&gt;像这样:

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 ;

答案 1 :(得分:4)

您可以使用std::getline逐行阅读,直到代码匹配为止,您可以将push_back名称std::vector添加到'|'。您还可以使用分隔符(例如bibi ceki|1 2 hasesh cekiii|1 3 krki cko|1 2 )构建文件,以便在名称和其余代码之前读取该字符。示例文件将是:

#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();
}

以下是如何实现这一目标的示例:

bibi ceki
krki cko

输出:

value = [[u"Seba", u"10"], [u"[Gianfranco", u"80"], [u"[Marco", u"20"], [u"[Massimo", u"125"]] 
相关问题