【发布时间】:2018-01-18 21:00:55
【问题描述】:
我正在编写一个提示用户输入 .txt 文件的程序,然后将 ifstream 对象和一个整数数组传递给一个函数 - count_letters(ifstream &, int *arrayInts)。
然后该函数从 ifstream 对象中读取每个字符并存储 a-z 中字符的频率(不区分大小写)。每个字符都被传递给一个 bool 函数,该函数检查它是否是非字母字符。为了便于阅读,我注释掉了 alphabetVect 和 checkVect 向量,因为它们很长。
此时我的程序退出执行。即使我可以看到返回为“真”,for 循环也不会执行。打印出 arrayInt 内容的函数结束之前的循环也永远不会执行。
void count_letters(std::ifstream &fileIn, int *arrayInt)
{
char c; // character variable to read from fileIn
bool cACReturn; // charArrayCheck return value
int aICount = 0; // count for arrayInt in for loop
std::vector<char> alphabetVect {// characters 'a' - 'z'};
while (fileIn.get(ch))
{
tempCh = ch;
cACReturn = charArrayCheck(ch);
std::cout << "cACReturn = " << cACReturn << std::endl;
while (1)
{
// If ch is an alphabetical character
if (cACReturn == true)
{
for (size_t i = 0; i < alphabetVect.size(); (i + 2))
{
if (ch == alphabetVect[i] || ch == alphabetVect[i + 1])
{
std::cout << "success" << std::endl;
arrayInt[aICount]++;
}
aICount++;
}
}
else
{
std::cout << "false" << std::endl;
}
}
}
for (int i = 0; i < 26; i++)
{
std::cout << "In count_letter letterArray[" << i << "] = " << arrayInt[i] << std::endl;
}
}
这里是 charArrayCheck 函数:
bool charArrayCheck(char charIn)
{
std::vector<char> checkVect {// non alphabet characters};
for (size_t i = 0; i < checkVect.size(); i++)
{
if (charIn == checkVect[i])
{
std::cout << "false in charArrayCheck" << std::endl;
return false;
}
else
{
if (i == (checkVect.size() -1))
{
return true;
}
else
{
continue;
}
}
}
}
感谢所有帮助。
【问题讨论】:
-
您的 for 循环不在函数中。那甚至不应该编译。
-
再次检查您的索引。
-
while (1) {...}你永远不会break跳出那个循环。 -
看起来你在复制代码时丢失了一些东西。
std::vector<char> alphabetVect {// characters 'a' - 'z'};无效。 -
请编辑您的问题以包含minimal reproducible example
标签: c++ arrays vector exit-code