Segmentation error while trying to save token from istream

My code crashes while reading from a file (see the end of this post). I declare the ifstream object basically by passing it through the buildGraph function (which takes ifstream & as a parameter) and tries to pass the first token to the temp string.

Corresponding code from the main:

#include <fstream>

int main() {

    ifstream infile1("data31.txt");

    if (!infile1) {
        cout << "File could not be opened." << endl;
        return 1;
    }

    GraphM G;
    G.buildGraph(infile1);
}

Relevant code from graphm.cpp:

#include <fstream>
#include <string>

void GraphM::buildGraph(ifstream& input)
{
    string temp;
    input >> temp;
}

There is a graphm.h header file, which also includes a stream. I spoke with several teachers who work in the college where I work, and they could not help at all, since they are just as confused as I am. The getline () function also causes a segmentation error, so this will not work. What am I doing wrong here?

Also, .txt, which I read from:

5
Aurora and 85th
Green Lake Starbucks
Woodland Park Zoo
Troll under bridge
PCC
1 2 50
1 3 20
1 5 30
2 4 10
3 2 20
3 4 40
5 2 20
5 4 25
0 0  0
3
aaa
bbb
ccc
1 2 10
1 3 5
2 3 20
3 2 4
0 0 0
+4
2

( )

SSCCE, :

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

class GraphM {
public:
    void buildGraph(ifstream& input);
};

void GraphM::buildGraph(ifstream& input)
{
    string temp;
    input >> temp;
    cout << temp;
}


int main() {
    ifstream infile1("data31.txt");

    if (!infile1) {
        cout << "File could not be opened." << endl;
        return 1;
    }

    GraphM G;
    G.buildGraph(infile1);
}

5.

, , , , 5. GNU ++ 4.7.3 cygwin Windows 7.

, , ?

0
    #include <fstream>
#include <iostream>
#include <string>

using namespace std;


void buildGraph(ifstream& input)
{
    string temp;

    for(int i=0; i<sizeof(input); i++)
    {
        input >> temp;
        cout<< temp;
    }
}


   int main()
   {

      ifstream infile1("test.txt");

      if (!infile1) 
      {  
        cout << "File could not be opened." << endl;
        return 1;
      }

      buildGraph(infile1);
   }

, ... , , , char *, , , .

0

Source: https://habr.com/ru/post/1537990/


All Articles