Search code examples
c++fileinputsubstringsubstr

Issue with substr C++


I am trying to make a program that reads a line from tst.txt using getline function. However when I try to get the substrings from it, I get an error that says method substr could not be resolved.

My code is the following.

#include <iostream>
#include <fstream>
#include <string>
#include <istream>
#include <sstream>
#include <stdlib.h>
using namespace std;

int main () {
    string line;
    string substr(int a, int b);
     string name[15];
     int a[15];
     int b[15];
    ifstream myfile ("tst.txt");
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            int i;
            getline (myfile,line);
            a[i]= myfile.substr(4,2);
            name[i]= myfile.substr(18,15);
            b[i]= myfile.substr(36,1);
            i=i+1;
            cout << a[i] <<" "<< b[i] << " "<< name[i] << endl;
        }
        myfile.close();
    }
    else cout << "Unable to open file";

    return 0;
}

Solution

  • As mentioned you can't call substr() with a std::ifstream. What you probably meant was to take the parts from the line string read in

            a[i]= stoi(line.substr(4,2));
            name[i]= line.substr(18,15);
            b[i]= stoi(line.substr(36,1));
    

    Also note you'll need to convert the substrings extracted to a number (instead of assigning them directly), hence I have added the stoi().


    As also mentioned in the comments on your question, you should do better error checks, and initialize all of your variables properly.
    Your while() loop can simply be rewritten as

    while (getline (myfile,line)) {
        // ...
    }
    

    The surrounding if() block

    if (myfile.is_open()) {
        // ...
    }
    

    can be omitted.