[英]Why is this char stopping my program?
Does the newline character have some kind of special significance in c++? 在C ++中,换行符是否具有某种特殊意义? Is it a non-ASCII character?
它是非ASCII字符吗?
I'm trying to build a Markov chain for each unique n-character substring within a larger piece of text. 我正在尝试为较大的文本中的每个唯一的n个字符子字符串构建一个马尔可夫链。 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).
每次遇到新的唯一子字符串时,我都会将其输入到映射中,该映射的值为256个元素的向量(扩展的ASCII表中的每个字符一个元素)。
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): 当我打印出文件的全部内容时没有问题(“ lines”是使用ifstream和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.
当我尝试将换行符返回到期望为char的函数时,就会发生问题。 "moveSpaces" is an integer constant that determines how many characters further ahead to move in the vector of strings on each iteration.
“ moveSpaces”是一个整数常量,它确定每次迭代时在字符串向量中向前移动多少个字符。
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). 我正在使用的文件是“圣诞节颂歌”(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. 您的
GetNextChar
函数假定如果您在某行的最后一个字符处,则在下一行中将有一个字符。 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. 第二行是空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.