0
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;
}
4

2 回答 2

3

改变

#define ISADIGIT "Is a digit";

#define ISADIGIT "Is a digit"

在您的情况下,可以比较指向您的字符串常量的指针,这与其他人所说的相反。

于 2012-10-11T15:24:44.820 回答
0

您当前问题的根本原因是宏定义末尾的分号(正如 piokuc 指出的那样)。预处理器语句不需要分号。这是您当前的实施需要考虑的另一件重要事情:

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

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

一般来说,不要使用字符串作为函数的返回码。字符串在 C 中不是真正的对象(与其他语言不同),在使用它们时存在很多隐藏的“陷阱”。从函数返回状态码的传统方法是使用整数作为返回值。函数成功完成时返回零,非零返回值表示某种错误。由于您已将所有错误代码抽象为宏,因此您只需将#define语句中的字符串替换为数字并将返回类型更改atoi2int. 您需要做的唯一其他更改是在您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
    ...
};
于 2012-10-11T16:08:38.260 回答