简体   繁体   中英

Why is this char stopping my program?

Does the newline character have some kind of special significance in c++? Is it a non-ASCII character?

I'm trying to build a Markov chain for each unique n-character substring within a larger piece of text. Every time I come across a new unique substring I enter it into a map whose value is a 256-element vector (one element for each character in the extended ASCII table).

There's no problem when I print out the entire contents of the file ("lines" is a vector of lines of text built using ifstream and getline):

for(int i=0; i<lines.size(); i++) cout << lines[i] << endl;

The whole text file shows up in the console. The problem happens when I try to return the newline character to a function that's expecting a char. "moveSpaces" is an integer constant that determines how many characters further ahead to move in the vector of strings on each iteration.

char GetNextChar(int row, int col){
    for (int i=0; i<MOVESPACES; i++) {
        if (col+1<lines[row].size()) {
            col+=1;
        } else {        // If you're not at the end of the line keep going
            row+=1;     // Otherwise, move to the beginning of the next row
            col=0;
        }
    }
    return lines[row].at(col);
}    

I've walked through with the debugger, and when it gets to the 1st column of the 2nd line it craps out on me – no error or anything. It fails within this function, not the calling function.

The file I'm using is A Christmas Carol (first thing that came up on Project Gutenberg). For reference here are the first few lines:

STAVE I:  MARLEY'S GHOST

MARLEY was dead: to begin with. There is no doubt
whatever about that. The register of his burial was

The function breaks when it should return the first character on the second line. This doesn't happen if I get rid of the newline, or if I build the "lines" vector myself line by line in the program. Any idea what's wrong?

Your GetNextChar function is assuming that if you are at the last character in some line, there will be a character in the next line. What happens if there is no character in that next line? This can happen in two places: When you have hit end of file, or when the next line is the empty string.

The second line is the empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM