有人知道这个while循环有什么问题吗?

时间:2019-03-18 03:46:02

标签: c++ while-loop

我正在使用while循环来遍历字符串,只要它在a-z内,但似乎不起作用?我觉得很奇怪,因为我在另一个函数中使用了相同的方法,除了0-9之外,而且那个函数工作得很好。

这是有问题的代码:

int lexicalAnalyzer::analyzeIdentifiers(char* program, int eos){
location = 0;
int num = 0;
int tempNum;

while(location != eos){
    tempNum = 0; //resetting counter
    while(program[location] >= 'a' && program[location] <= 'z'){ #ERROR here Thread 1: EXC_BAD_ACCESS (code=1, address=0x101d00000)
        tempNum++; //using  tempNum to catch whether identifiers are being 
found
        location++;
    }

    if(tempNum == 1){
        //meaning only 1 char was caught
        num++;
        identifiers[0] = identifiers[0] + 1;
    }else if(tempNum > 0){
        //meaning char ident was caught
        num++;
        identifiers[1] = identifiers[1] + 1;
    }
    location++;
}//end of while
return num;
}

这是可以正常工作的

int lexicalAnalyzer::analyzeIntegers(char* program, int eos){
location = 0;
int num = 0;
int tempNum;

while(location != eos){
    tempNum = 0; //resetting counter
    while(program[location] >= '0' && program[location] <= '9'){
        tempNum++; //using  tempNum to catch whether integers are 
being found
        location++;
    }

    if(tempNum == 1){
        //meaning only a digit was found
        num++;
        integers[0] = integers[0] + 1;
    }else if(tempNum > 0){
        //meaning integer was caught
        num++;
        integers[1] = integers[1] + 1;
    }
    location++;
}//end of while
return num;
}

我不确定我是否看不到有什么问题,但是我确实复制并粘贴了analyzerInteger函数,并为analyzerIdentifiers进行了少许修改,但仍无法正常工作?

location是已初始化的私有类变量

1 个答案:

答案 0 :(得分:1)

我建议对您的功能进行以下更改。

  1. 将第一个while循环的条件更改为:

    while ( location <= eos ) {
    

    这将确保如果在循环中将location递增以使其跳过eos,则循环将终止。

  2. 更改内部while循环的条件以添加类似的检查。

    while ( location <= eos &&
            program[location] >= '0' && program[location] <= '9' ) {
    
  3. 使用std::isdigit而不是使用硬编码数字。

    while ( location <= eos && std::isdigit(program[location]) ) {
    

在外部循环中program中终止空字符的附加检查会更好。

    while ( location <= eos &&
            program[location] != '\0' ) {