I have just become familiar with substr. I had been using it successfully the past couple days until I ran into this first problem, and now I have begun to question if I actually know how it works. I have some code posted below which reads an input text file and outputs some substrings. For whatever reason, the first parameter of substr (the position part) seems to be off by 3 characters. The line that reads "var_number = line[0].substr(17,11);" seems to function as if the 17 value is really set to 14.
I read about how to use substr here: substr - C++ Reference. Based upon what I read, I would think I am using substr correctly, but apparently I am not, given the output I am creating. Do you guys see what the problem is?
The code:
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line[115];
int x = 0;
int i = 0;
char filename[50];
string var_number;
string var_time;
cout << "filename equals: ";
cin >> filename;
ifstream myfile (filename);
if (myfile.is_open())
{
while (myfile.good())
{
getline (myfile,line[i]);
i++;
}
myfile.close();
}
else cout << "Unable to open file";
// LINE 0 VARIABLES
x = line[0].length();
// handnumber
var_number = line[0].substr(17,11);
// time
var_time = line[0].substr(x - 11,11);
cout << var_number << endl;
cout << var_time << endl;
system("pause");
return 0;
}
The input text:
012345678901234 #54277040317 Blah Blah Blah 20:35:38 ET
Blah Blah Blah
Blah Blah Blah
Blah Blah Blah
The output text: