从函数返回值比较C中的宏

时间:2012-10-11 15:17:42

标签: c unix

if (ISADIGIT != atoi2(&word[i])){

为什么我不能这样做(见上文)。我得到“期待的表达”?

#include <ctype.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>

#define STARTSWITH0 "Starts with 0";
#define NEGATIVESIGNNOTATBEGINNING "Negative sign not at beginning";

#define ISADIGIT "Is a digit";

#define MORETHANONENEGATIVESIGN "More than one negative sing";
#define MORETHANONEDECIMALPLACE "More than one decimal place";
#define NUMBERTOOLARGEORNUMBERTOOSMALL "Number too large or number too small";
#define CONVERSIONERROR "Conversion Error";
#define CANNOTCONTAINLETTERS "Cannot contain letters";

char* atoi2(char str[]);
int main(int argc, char ** argv){

    char c, word[1000]; int count;


        printf("enter word: ");
        count = 0;

        while(1){
            c = getchar();
            if (c == EOF); 
                return 0;

            if (c == ' ') {
                continue;
            }

            if (c == '\n' || c == '\t'){
                word[count] = '\0';
                break;
            }
            word[count++] = c;
        }
        int i;


    for (i = 0; i < count; i++){

        if (ISADIGIT != atoi2(&word[i])){
            printf("%s\n", atoi2(&word[i]));
            return 1;
        }

    }

    int sum;
    for (i = 0; i < count; i++){
        sum += word[i];
    }

    printf("sum is: %d", sum);


}


char* atoi2(char * str)
{
    int i, v, d, n, errno;
    i = v = d = n = 0;

    while(str[i] != '\0'){

        /* this means the first value is a 0, therefore it should not be numeric */
        if (i == 0 && str[i] == '0' && str[i+1] != '.' && str[i+1] != '\0') return STARTSWITH0;

        if(!isdigit(str[i])) {

            if (isalpha(str[i])) return CANNOTCONTAINLETTERS; /* must make sure the digit we receive is not a letter */

            if (str[i] == '-'  && i > 0) return NEGATIVESIGNNOTATBEGINNING; /* negative sign must come first */

            if (str[i] == '-'){ ++n; ++i; continue; } /* first negative sign, pass through */

            if (str[i] == '.') { ++d; } /* periods are ok, just not too many */

        }
        ++i;
    }

    if (n > 1) return MORETHANONENEGATIVESIGN; /* can't have more than one negative sign */

    if (d > 1) return MORETHANONEDECIMALPLACE; /* this means there is more than one decimal place */

    return ISADIGIT;
}

感谢您提供的所有精彩内容。这是修改后的程序

#include <ctype.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>

#define STARTSWITH0 1 /*"Starts with 0"*/
#define NEGATIVESIGNNOTATBEGINNING 2 /*"Negative sign not at beginning"*/
#define MORETHANONENEGATIVESIGN 3 /*"More than one negative sing"*/
#define MORETHANONEDECIMALPLACE 4 /*"More than one decimal place"*/
#define NUMBERTOOLARGE 5
#define CANNOTCONTAINLETTERS 6 /*"Cannot contain letters"*/
#define CONTAINSAPERIOD 7 /*"Integers cannot contain decimal points"*/

int atoi2(char *);
char * geterrorstring(int);
int main(int argc, char ** argv){

    char c, nums[1000][1000];

    while(1) {
        printf("enter numbers: ");
        int digits = 0, row = 0, maxrows = 1;

        /* gets data from user, puts it into an array */
        while(1){
            c = getchar();
            if (c == EOF) return 0;
            if (c == ' ' || c == '\t') { nums[row][digits] = '\0'; row++; maxrows++; digits = 0; }
            if (c == '\n'){ nums[row][digits] = '\0'; maxrows++; digits = 0; break; }
            nums[row][digits++] = c;
        }

        int i, j;

        int error = 0;

        /* sums up data from array and prints error message if digit is invalid */
        int sum = 0, msg = 0;
        for (i = 0; i < maxrows; i++){
                msg = atoi2(nums[i]);
                if (msg > 0){
                    printf("%s\n", geterrorstring(msg));
                    error = 1;
                }
            sum += atoi(nums[i]);
        }

        if (error == 1) continue;

        printf("sum is: %d\n", sum);

    }

}

char * geterrorstring(int code)
{
    switch (code) {
        case STARTSWITH0:
            return "Starts with 0";
            break;

        case NEGATIVESIGNNOTATBEGINNING:
            return "Negative signs must be at the begging of the number";
            break;

        case MORETHANONENEGATIVESIGN:
            return "You cannot have more than one negative sign in a number";
            break;

        case MORETHANONEDECIMALPLACE:
            return "More than one decimal place";
            break;

        case NUMBERTOOLARGE:
            return "Number too large";
            break;

        case CANNOTCONTAINLETTERS:
            return "Cannot contain letters";
            break;

        case CONTAINSAPERIOD:
            return "Integers do not have decimal places";

        default:
            return "I have no idea what error you have, but you got one";
            break;
    }
}


int atoi2(char * str)
{
    int i, v, n, errno;
    i = v = n = 0;

    while(str[i] != '\0'){

        /* this means the first value is a 0, therefore it should not be numeric */
        if (i == 0 && str[i] == '0' && str[i+1] != '.' && str[i+1] != '\0') return STARTSWITH0;

        if(!isdigit(str[i])) {

            if (isalpha(str[i])) return CANNOTCONTAINLETTERS; /* must make sure the digit we receive is not a letter */

            if (sizeof(atoi(str)) > sizeof(int)) return NUMBERTOOLARGE; /* make sure number is not that large */

            if (str[i] == '-'  && i > 0) { if (n > 1) { return MORETHANONENEGATIVESIGN; } return NEGATIVESIGNNOTATBEGINNING; } /* negative sign must come first */

            if (str[i] == '-'){ ++n; ++i; continue; } /* first negative sign, pass through */

            if (str[i] == '.') { return CONTAINSAPERIOD; } /* periods are ok, just not too many */

        }
        ++i;
    }

    if (n > 1) return MORETHANONENEGATIVESIGN; /* can't have more than one negative sign */

    return 0;
}

2 个答案:

答案 0 :(得分:3)

更改

#define ISADIGIT "Is a digit";

#define ISADIGIT "Is a digit"

在你的情况下,将指针与你的字符串常量进行比较是可以的,这与其他人所说的相反。

答案 1 :(得分:0)

你的直接问题的根本原因是宏定义结束时的分号(正如piokuc指出的那样)。预处理器语句不需要分号。这是您当前实现的另一个重要事项:

由于ISADIGIT是一个宏,预处理器将使用指定的字符串替换代码中的ISADIGIT的每个实例。您在多个位置使用ISADIGIT,每个都将被字符串替换。其中每一个都将被视为一个独立的独立字符串文字。它们的内容恰好相同,但它们是不同的对象。这意味着您的atoi2函数将返回指向函数内包含的字符串文字的指针,并且您的main函数正在将该指针与指向main中包含的字符串文字的指针进行比较。由于这些是指向不同对象的指针,因此它们总是比较不相等。就编译器而言,它们是恰好包含相同内容的字符串这一事实并不重要。

话虽如此,在某些情况下,此代码可能出现。一些编译器具有可选的优化,通过组合相同的字符串文字来节省空间。在这种情况下,ISADIGIT宏的扩展将归结为指向常见字符串文字的指针,并且您在main中进行的比较可以起作用。但是,您永远不应该依赖特定的编译器优化来使您的代码正常工作。如果你这样做,如果升级你的编译器,用不同的编译器构建,构建一个'debug'版本而不是'release'版本等,你将面临代码破坏的强大风险。

通常,不要将字符串用作函数的返回码。字符串不是C中的真实对象(与其他语言不同),并且在使用它们时会涉及许多隐藏的“陷阱”。从函数返回状态代码的传统方法是使用整数作为返回值。函数成功完成后返回零,非零返回值表示某种错误。由于您将所有错误代码抽象为宏,因此您只需将#define语句中的字符串替换为数字,并将atoi2的返回类型更改为int。您需要进行的唯一其他更改是printf("%s") atoi2的返回值。您需要使用单独的方法将整数转换为字符串。执行此操作的两种常用方法是使用函数或表:

// Function method:
// Use like: printf("%s", code_to_string(code));
const char* code_to_string(int code) {
    switch(code) {
        case STARTSWITH0:
            return "Starts with 0";
        case NEGATIVESIGNNOTATBEGINNING:
            return "Negative sign not at beginning";
        ...
        default:
            return "Unknown error";
    }
}

// Table method (assumes error codes are numbered 1,2,3,...
// Use like: printf("%s", error_strings[code]);
const char* error_strings[] = {
    "No error", // 0
    "Starts with 0", // 1
    "Negative sign not at beginning", // 2
    ...
};