Using c++, why am I getting the error message “string subscript out of range” when I know it is not? Or at least it seems that way

StackOverflow https://stackoverflow.com/questions/10097725

Question

EDIT - there are no blank lines. EDIT 2 - my bad, it seems I was wrong all along. There is a blank line somewhere, although the csv file indicates otherwise. It's working now. Okay so here is the entire (short) program:

#include <iostream>
#include <cctype>
#include <string>
#include <fstream>
using namespace std;

int main(){
    char a;
    string stringmanip;

    fstream myfile("readthisfile.csv");
    if (myfile.is_open()){
        while ( myfile.good() ){
            getline(myfile,stringmanip);
            a=stringmanip[0];
        }
        myfile.close();
    }
    else cout<< "Unable to open file";

    return 0;
}

It makes no sense to me. I can copy stringmanip, I can cout stringmanip, I can use .substr with stringmanip. If I define a regular string I can use the [] operation just fine. I've tried .at as well, but that only leads to another error. (Out of range).

Any help would be GREATLY appreciated. Sorry I'm such a beginner, as I'm sure you can tell.

Thanks, Ben

Was it helpful?

Solution

If readthisfile.csv has an empty line at the end of the file (or anywhere in the file), then you will get back an empty string. You can't dereference the 0th character of an empty string. string::operator[] only accepts indices from 0 to string::length() - 1. If you have an empty string, any call to string::operator[] will result in undefined behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top