我正在我的 C++ 类(class)中研究一个自动摘要系统,并且对我正在做的一个 ASCII 比较有疑问。这是代码:
char ch;
string sentence;
pair<char, char> sentenceCheck;
int counter = 0;
while (!ifs2.eof())
{
ch = ifs2.get();
ch = tolower(ch);
if (ch == 13)
ch = ifs2.get();
if (ch != 10 && ch != '?' && ch != '!' && ch != '.')
sentence += ch;
sentenceCheck.first = sentenceCheck.second;
sentenceCheck.second = ch;
cout << sentenceCheck.first << "-" << (int)sentenceCheck.first << " ---- " << sentenceCheck.second << "-" << (int)sentenceCheck.second << endl;
if(sentenceCheck.second == ' ' || sentenceCheck.second == 10 || sentenceCheck.second == -1)
{
if(sentenceCheck.first == '?' || sentenceCheck.first == '!' || sentenceCheck.first == '.')
{
istringstream s(sentence);
while(s >> wordInSentence)
{
sentenceWordMap.insert(pair<string, int>(wordInSentence, 0));
}
//sentenceList.push_back(pair<string, int>(sentence, 0));
sentence.clear();
}
}
}
这里(使用两个 if 语句)所做的是检查文本中是否开始了一个新句子,以便稍后分析和处理。条件有效,但只是因为我们发现我们也必须检查 -1。有什么想法吗?
最佳答案
-1 在 ASCII 中不代表任何内容。所有 ASCII 码都在 [0, 127] 范围内。 C++ 甚至不能保证 -1
是 char
的有效值.
问题是您没有检查 ifs2.get()
的返回值,它返回一个 int
(不是 char
!)可能是 -1
在文件末尾。检查这个的正确方法是
int ch = ifs2.get();
if (!ifs2)
// break the loop
因为EOF值不保证是-1
(实际上是 std::char_traits<char>::eof()
)。
(顺便说一句,您不应该将 ASCII 代码写成魔数(Magic Number);使用 \n
换行,使用 \r
回车。)
关于c++ - -1在ASCII中代表什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9517451/