Getting RWBoundsErr while reading a text file using RWCString in C++

312 Views Asked by At

Following code is giving me RWBoundsErr error

terminate called after throwing an instance of 'RWBoundsErr'

bool filterData()
{       
    while(!inputFile_.eof())
    {
        currentLine_.readLine(inputFile_);        
        //outputFile_<<currentLine_(0,1)<<currentLine_(2,1)<<currentLine_(4,13)<<currentLine_(0,1)<<currentLine_(2,1)<<currentLine_(4,13)<<endl;
        outputFile_<<currentLine_[0]<<currentLine_[2]<<currentLine_(4,13)<<currentLine_[0]<<currentLine_[2]<<currentLine_(4,13)<<endl;        
    }
    return (TRUE);
}

But if I use the commented out line instead, everything is working as expected.

currentLine_ is of data type RWCString

outputFile_ and inputFile_ has the path of the inout/output txt files

Sample contents of the text file

ABCD1234567890123 2017/10/16 13:40:28 
WXYZ9876543210987 2017/10/16 13:40:28 

Please note that there is a trailing space at the end of each line

Even though I have identified the solution to this issue, I would like to understand why this code is failing.

1

There are 1 best solutions below

2
sg7 On

Take a look at the documentation related to operator<<() operator for RWCString:

RWvostream&
operator<<(RWvostream&, const RWCString& str);
RWFile&
operator<<(RWFile&,     const RWCString& str);
Saves string str to a virtual stream or RWFile, respectively.

and RWFile:

RWFile&
operator<<(RWFile&,     const RWCString& str);
Saves string str to a virtual stream or RWFile, respectively.
...
RWFile&
operator<<(RWFile&,     const RWInteger& x);
Saves the RWInteger x to a virtual stream or RWFile, respectively.

There is no << operator which would take a char.

currentLine_(0,1) is a substring which can be used with << operator

RWCSubString
operator()(size_t start, size_t len);
RWCConstSubString
operator()(size_t start, size_t len) const;

On the other hand the currentLine_[0] is a char

char&
operator[](size_t i);
char
operator[](size_t i) const;
Returns the ith byte.

In your case the attempt to use char with the << operator causes the RWBoundsErr error.