Extra number when reading in from a file and using substr().

Nov 15, 2014 at 11:06pm
Hey guys for some reason I'm getting an extra number when I read data from a file and then try and use substr() on the string I just read in. Any help would be greatly appreciated!

Here's the data from the file I'm reading from:
i 35
i 56
i 69

Here's the output from the program with out the if statement:
i 34 35
i 56 57
i 69 70
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 2) > this->size() (which is 0)
Aborted (core dumped)

Output with the if statement:
i 34 35
i 56 57
i 69 70
70



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sstream>

using namespace std;

int string_to_int(string s){
   istringstream instr(s);
   int n;
   instr >> n;
   return n;
}



using namespace std;

int main()
{
  ifstream openFile;
  openFile.open("test.txt");
  string readLine;
  int number = 0;
  char c ;
      while(!openFile.eof())
        {
             getline(openFile, readLine);
              c = (char)readLine[0];
              if(readLine.size() > 0)
              readLine = readLine.substr(2,readLine.size()-2);
              number = string_to_int(readLine);
              //  if(c == 'i')
             //   cout<<"omg its an i"<<endl;
             cout<< c << " " << readLine<< " "<< number + 1 <<endl;


        }
  openFile.close();
}
Nov 15, 2014 at 11:30pm
while(!openFile.eof()) This is the problem. You should not loop on eof() unless you know how it is work. eof bit will not set until read operation will attempt to extract past-the-end symbol. So you will try to read one more line than there is in a file. This unexisting string is probably 0 length and attempt to call substring on it fails.
Quick fix:
1
2
3
4
while(getline(openFile, readLine))   
{
    c = (char)readLine[0];
    //... 
Nov 15, 2014 at 11:38pm
Thank you for the help!
Topic archived. No new replies allowed.