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

4

1 回答 1

4

如果 readthisfile.csv 在文件末尾(或文件中的任何位置)有一个空行,那么您将返回一个空字符串。您不能取消引用空字符串的第 0 个字符。string::operator[]只接受从0to 的索引string::length() - 1。如果您有一个空字符串,任何调用都string::operator[]将导致未定义的行为。

于 2012-04-10T23:17:23.343 回答