-1

I am new to C++ (I usually use Java) and am trying to make a k-ary heap. I want to insert values from a file into the heap; however, I am at a loss with the code for the things I want to do.

I wanted to use .nextLine and .hasNextLine like I would in Java with a scanner, but I am not sure those are applicable to C++. Also, in the file the items are listed as such: "IN 890", "IN 9228", "EX", "IN 847", etc. The "IN" portion tells me to insert and the "EX" portion is for my extract_min. I don't know how to separate the string and integer in C++ so I can insert just the number though.

int main(){


    BinaryMinHeap h;

    string str ("IN");
    string str ("EX");
    int sum = 0;
    int x;
    ifstream inFile;

    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

    while (inFile >> x) {
        sum = sum + x;
        if(str.find(nextLin) == true //if "IN" is in line)
        {
            h.insertKey(nextLin); //insert the number 
        }
        else //if "EX" is in line perform extract min
    }

    inFile.close();
    cout << "Sum = " << sum << endl; 
}

The result should just add the number into the heap or extract the min.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jacob Wynn
  • 23
  • 6

1 Answers1

0

Look at the various std::istream implementations - std::ifstream, std::istringstream, etc. You can call std::getline() in a loop to read a std::ifstream line by line, using std::istringstream to parse each line. For example:

int main() {
    BinaryMinHeap h;
    string line, item;
    int x sum = 0;
    ifstream inFile;

    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
        return 1; // terminate with error
    }

    while (getline(inFile, line)) {
        istringstream iss(line);
        iss >> item;
        if (item == "IN") {
            iss >> x;
            sum += x;
            h.insertKey(x);
        }
        else if (item == "EX") {
            // perform extract min
        }
    }

    inFile.close();
    cout << "Sum = " << sum << endl;

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770