返回值不会改变,总是返回0

时间:2019-05-20 18:11:16

标签: c function

我对编码有点陌生,我需要完成以下工作:我需要用C语言编写一个函数,以检查给定的字符串格式是否正确,如果不正确,则应返回0。该字符串应仅包含字母和定界符“-”。因此,例如:“ aAa-bBb”是正确的,因此返回值应为1,但对于“ a-1-bB3”,它应返回0。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int functiontest(char* text){
   char* piece = strtok(text," - ");  //breaks the given string into 
   int returnvalue = 1;               //smaller strings

    while (piece != NULL) {
        for (int x = 0; x < strlen(piece); x++) {
            if ((isalnum(piece[x]))) {
                returnvalue = 1;
            } else {
                returnvalue = 0;
                break;
            }  
        }                                 

        piece = strtok(NULL," - ");
    }

    return returnvalue;
}

int main() {
    char texttest[11] = "akod - kljp";

    printf("%s", &texttest);

    int test = functiontest(texttest);

    printf("\n%d",test);
    return 0;
}

无论我如何更改texttest字符串,该函数始终返回0。这是怎么回事?

1 个答案:

答案 0 :(得分:0)

您的中断处于错误的条件块中。如果每个数字都有一个数字,则返回值将为1。基本上,您编写的内容将在第一次出现非数字时返回0。由于输入中包含非数字字符,因此它始终为0。3333将返回1,而3-将返回0;没有包含数字的字符串将永远不会返回1。