gpt4 book ai didi

c++ - while 循环看不到或找不到终止空字符

转载 作者:搜寻专家 更新时间:2023-10-31 00:37:26 25 4
gpt4 key购买 nike

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

#include <iostream>

using namespace std;

int main()
{


char fullString[200]={'\0'}; // Declare char string of 200, containing null characters
int alphaCount = 0;
int charCount = 0;
int wordCount = 0;

cin.getline(fullString,200); //
cout << "\n\n" << fullString;
cout << "\n\n\n";

int i=0;
int i2 = 0;
while(fullString[i]!='\0'){ //iterate through array until NULL character is found

cout << "\n\nIndex 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 << "\n\ntest1";

}
i2 = i; // assign value of 'i' to 'i2' which is the next position of a character in the array

if(fullString[i] == '\0')
{
cout << "\n\nNull Character " << endl;
cout << "found at pos: " << i << endl;
}

}

cout << "\n\ni" << i;
cout << "\n\nWord" << wordCount;

return 0;

最佳答案

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

这很容易通过改变你的 while 条件来解决:

while(fullString[i2]!= ' ')

...为此:

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

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

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

关于c++ - while 循环看不到或找不到终止空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19812254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com