虽然循环没有看到或找到终止的空字符

While loop not seeing or finding terminating null character

本文关键字:终止 字符 循环      更新时间:2023-10-16

>我正在尝试使用使用"\0"作为终止条件的while循环遍历字符数组,但我的问题是直到索引位置481才找到"\0",数组被声明为200长,我看不出我做错了什么!!在任何人询问之前,我不能为此使用字符串或任何形式的字符串函数。谁能帮忙??

#include <iostream>
using namespace std;
int main()
{

char fullString[200]={''}; // Declare char string of 200, containing null characters
int alphaCount = 0;
int charCount = 0;
int wordCount = 0;
cin.getline(fullString,200); //
cout << "nn" << fullString;
cout << "nnn";
int i=0;
int i2 = 0;
while(fullString[i]!=''){ //iterate through array until NULL character is found
    cout << "nnIndex pos : " << fullString[i]; //Output char at 'i' position

   while(fullString[i2]!= ' '){ //while 'i' is not equal to SPACE, iterate4 through array
        if(isalpha(fullString[i2])){
            alphaCount++; // count if alpha character at 'i'
        }
        charCount++; // count all chars at 'i'
        i2++;
    }
    if(charCount == alphaCount){ // if charCount and alphaCount are equal, word is valid
        wordCount++;
    }
   charCount = 0; // zero charCount and alphaCount
   alphaCount = 0;
   i=i2;// Assign the position of 'i2' to 'i'
   while(fullString[i] == 32){ //if spaces are present, iterate past them
        i++;
        cout << "nntest1";
   }
    i2 = i; // assign value of 'i' to 'i2' which is the next position of a character in the array
    if(fullString[i] == '')
    {
        cout << "nnNull Character " << endl;
        cout << "found at pos: " << i << endl;
    }
}
cout << "nni" << i;
cout << "nnWord" << wordCount;
return 0;

}

正如其他人指出的那样,您的问题出在内部循环上。您测试空格字符但不测试 NULL,因此它会迭代到最后一个单词的末尾,因为最后一个单词之后没有空格字符。

这可以通过更改您的 while 条件来轻松修复:

while(fullString[i2]!= ' ')

。对此:

while(fullString[i2] && fullString[i2]!= ' ')

这会更改您的内部 while 循环,首先测试非 NULL,然后测试非空格。

我没有纠正你的其余代码,因为我认为这是一个类项目(看起来像一个),所以我将我的回答限制在你的问题范围内。

您不签入内部循环

   while(fullString[i2]!= ' '){ //while 'i' is not equal to SPACE, iterate4 through array
        if(isalpha(fullString[i2])){
            alphaCount++; // count if alpha character at 'i'
        }
        charCount++; // count all chars at 'i'
        i2++;
    }
...
i=i2;// Assign the position of 'i2' to 'i'

下一个字符是否等于"\0"

这是因为内部循环不检查终止,它们只是继续循环,甚至超过字符串的末尾。


顺便说一句,如果您想计算单词,空格和非空格字符的数量,C++有更简单的方法。参见例如 空格和字符的std::countstd::count_if。例如:

std::string input = "Some stringtwith   multiplenspaces in it.";
int num_spaces = std::count_if(std::begin(input), std::end(input),
    [](const char& ch){ return std::isspace(ch); });

对于计算单词,您可以使用std::istringstreamstd::vectorstd::copystd::istream_iteratorstd::back_inserter

std::istringstream iss(input);
std::vector<std::string> words;
std::copy(std::istream_iterator<std::string>(iss),
          std::istream_iterator<std::string>(),
          std::back_inserter(words));

在上面的代码之后,words向量的大小是字数。

如果您使用例如 std::copy_if,您也可以将上面的代码用于其他情况(但std::count_if更适合单字符类)。