c ++从包含特定元素的文件中的一组元组中检索模式

时间:2017-08-25 14:26:13

标签: c++ file tuples

我有一个文本文件,其中每一行都是以下形式的元组:

number name1 name2 boolean

其中“boolean”是一个0或1的bool变量。

我想读取文件并显示包含相同编号的所有元组。 我有以下代码,在编译后没有给我任何错误,但在引入它停止工作的数字之后。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{


    int a,e;
    string str1, str2, line;
    bool b;

  printf ("Enter pattern number: ");
  scanf ("%i",e);

  ifstream myfile ("entry.txt");
  if (myfile.is_open())
  {
    while ( myfile >> a >> str1 >> str2 >> b )
    {

        if (a==e)
        {

        cout << a << ' ';
        cout << str1 << ' ';
        cout << str2 << ' ';
        cout << b << '\n';

    myfile.close();
    }
  }
}

  else cout << "Unable to open file"; 

  return 0;
}

1 个答案:

答案 0 :(得分:1)

您必须将变量的地址传递给scanf(),以便它可以修改变量。将int传递给期望int*的函数具有UB。

所以传递一个地址 - &gt;使用引用(&)运算符

scanf ("%i",e)

scanf ("%i",&e)

并且效果很好。

或仅使用std::cin流。

std::cin >> e;