Problem with substr()

Hi, new member here
I am trying to extract filenames from a file.
When my string is preset the code works ok but
when I read lines in from a file it does not work.
Can anyone see the error of my ways.

Many thanks in advance, Paul.

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
43
44
45
46
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

main()
{
   string filename;
   string str1;
   
   // Why won't it work when reading from a file
   ifstream myfile ("data.txt");
   if (myfile.is_open())
   {
      while (! myfile.eof() )
      {
            getline (myfile,str1);

            //string str1( "p4 = file128.dat, 128" ); // This works ok
            string::size_type pos1 = str1.find( "=", 0 );
            string::size_type pos2 = str1.find( ",", 0 );
   
            cout << str1 << endl;

            // Extract the filename
            filename = str1.substr (pos1 + 2,((pos2 - pos1)-2));// substr fault with files ?
            cout << filename << endl;
      }
      
    myfile.close();
  }
   system("PAUSE");	
}

// This is the data.txt file to be opened
/*
'ignore any lines that start with a comment
'ignore any lines that start with a comment

p1 = file1.dat, 0
p2 = file2.dat, 2
p3 = file22.dat, 22
p4 = file100.dat, 100
*/


Program should output...

file1.dat
file2.dat
file22.dat
file100.dat
Last edited on
It works fine for me.

But you don't account for lines that aren't of the form

"x = y, z"

You must, at the very least, account for blank lines. If you plan to have commentary you'll also want to check for and skip those lines.

Good luck!
Yes, thank you Duoas.

Substr Pos1 and pos2 are reading out of bounds and causing the error when passed a blank line. Problem fixed :)

Regards Paul

Topic archived. No new replies allowed.