0

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

  • 3
    Does your file contain any blank lines? Also, [please get rid of](http://www.gidnetwork.com/b-61.html) the `system("pause");`. (I almost ran your code to test it, and on my system, there's a command called `pause` that shuts down the cooling system on my home reactor.) – David Schwartz Apr 10 '12 at 23:13
  • sorry, I got rid of it. No, it doesn't contain any blank lines. –  Apr 10 '12 at 23:22

1 Answers1

4

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.

MSN
  • 53,214
  • 7
  • 75
  • 105
  • 4
    +1 Also, `while ( myfile.good() )` should be `while ( getline(myfile, stringmanip) )`. I wish the whole `while(!stream.eof())`/`while(stream.good())` antipattern would just die already. – ildjarn Apr 10 '12 at 23:19
  • Haha,can't stress how new I am, sorry. –  Apr 10 '12 at 23:23