安全地在C中添加两个数字


24

众所周知,C是一种可爱,安全,高级的编程语言。但是,作为编码员,您需要设置以下任务。

编写一个程序,将两个数字相加。

  • 输入:两个以空格分隔的整数。
  • 输出:输入中两个数字的总和。

不同之处在于您的代码必须是100%安全的。换句话说,无论输入是什么,它都必须正常运行。如果输入确实是两个用空格分隔的整数,且两个整数均小于100位,则必须输出和。否则,它必须输出错误消息并安全退出。

到底有多难?

病理输入案例会给别人以其他的答案:)

使用ubuntu上的gcc -Wall -Wextra,代码必须在没有警告的情况下进行编译。


澄清。

  • 输入来自标准输入。
  • 水平空格仅是单个空格字符。第一个数字前不应有任何内容,并且输入应以换行符+ EOF或仅以EOF终止。
  • 增强Backus-Naur形式指定的唯一有效输入是:
    NONZERODIGIT =“ 1” /“ 2” /“ 3” /“ 4” /“ 5” /“ 6” /“ 7” /“ 8” /“ 9”
    POSITIVENUMBER = NONZERODIGIT * 98DIGIT
    NEGATIVENUMBER =“-” POSITIVENUMBER
    NUMBER = NEGATIVENUMBER / POSITIVENUMBER /“ 0”
    VALIDINPUT = NUM​​BER SP NUMBER * 1LF EOF
  • 错误消息是单个字母“ E”,后跟新行。
  • 无论输入是什么,代码都必须在不到0.5s的时间内完全终止。
code-golf  c 

2
我喜欢单用“否则”一词会使您的规范变得多么清晰。(我认为)写得很好。遗憾的是,挑战仅存在于C语言中,但我可以理解为什么必须这样做。
Rainbolt 2014年

3
没有警告+代码高尔夫球+ C?这注定会很有趣!
Fors

1
标准输入或命令行?
吱吱作响的ossifrage,2014年

2
我们可以得到严格可接受的输入格式吗?例如,第一个数字之前没有多余的空格(或任何非数字的东西),两个数字之间没有任何数量的水平空白(即,水平制表符和空格),第二个之后除了换行符或回车符以及换行符之外没有其他内容数?
Fors

3
此外,以空格分隔的平均值是否表示1)由ASCII值32、1的一个字符分隔,2)由ASCII值32、3)的任意数量的任意一个ASCII空格字符(32、10、9,可能是13)分隔的字符?),4)从ASCII空白字符集中任意数量的单个空白字符分隔开来,或5)由任意数目的ASCII空白字符集中的任意组合分隔开?
user12205 2014年

Answers:


4

6610字节(最小)

满足所有挑战标准的“好孩子” C程序。对负数使用10s补码。还包括测试工具和测试用例。

/*
Read input from STDIN. The input must conform to VALIDINPUT:

    NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
    POSITIVENUMBER = NONZERODIGIT *98DIGIT
    NEGATIVENUMBER = "-" POSITIVENUMBER
    NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
    VALIDINPUT = NUMBER SP NUMBER *1LF EOF

Check syntax of input. If input is correct, add the two numbers and print
to STDOUT.

LSB => least significant byte
MSB => most significant byte
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
#define NUL ('\0')
/*
    maximum characters in VALIDINPUT:
        '-'     1
        POSITIVENUMBER  MAXDIGITS
        ' '     1
        '-'     1
        POSITIVENUMBER  MAXDIGITS
        LF      1
*/
#define MAXDIGITS (99)
#define MAXVALIDINPUT (2*MAXDIGITS+4)

void die() { printf("E\n"); exit(1); }

/*
    Add two NUMBERs and print the result to STDOUT.  The NUMBERS have
been separated into POSITIVENUMBERS and sign information.

Arguments:
    first       - pointer to LSB of 1st POSITIVENUMBER
    firstSize   - size of 1st POSITIVENUMBER
    firstNegative   - is 1st # negative?
    second      - pointer to LSB of 2nd POSITIVENUMBER
    secondSize  - size of 2nd POSITIVENUMBER
    secondNegative  - is 2nd # negative?
    carry       - carry from previous place?

Returns:
    sum[]       - sum
    addNUMBERs()    - carry to next place?

- Don't use complementDigit(popDigit(p,s),n). Side-effects generate two pops.
*/
#define popDigit(p,s) ((s)--,(*(p++)-'0'))
#define complementDigit(c,n) ((n) ? 9-(c) : (c))

#define pushSum(c) (*(--sumPointer)=(c))
#define openSum() (pushSum(NUL))
#define closeSum() ;
char    sum[MAXVALIDINPUT];
char    *sumPointer = sum+sizeof(sum);
int addNUMBERs(char *first, int firstSize, bool firstNegative,
        char *second, int secondSize, bool secondNegative,
        int previousCarry) {
    int firstDigit, secondDigit;
    int mySum;
    int myCarry;

    /*
        1st half of the problem.

        Build a stack of digits for "first" and "second"
    numbers. Each recursion of addNUMBERs() contains one digit
    of each number for that place. I.e., the 1st call holds
    the MSBs, the last call holds the LSBs.

        If negative, convert to 10s complement.
    */
    assert((firstSize > 0) && (secondSize > 0));
    if (firstSize > secondSize) {
        firstDigit = popDigit(first, firstSize);
        firstDigit = complementDigit(firstDigit, firstNegative);
        secondDigit = 0;
    } else if (secondSize > firstSize) {
        firstDigit = 0;
        secondDigit = popDigit(second, secondSize);
        secondDigit = complementDigit(secondDigit, secondNegative);
    } else {
        //  same size
        firstDigit = popDigit(first, firstSize);
        firstDigit = complementDigit(firstDigit, firstNegative);
        secondDigit = popDigit(second, secondSize);
        secondDigit = complementDigit(secondDigit, secondNegative);
    }

    //  recursion ends at LSB
    if ((firstSize == 0) && (secondSize == 0)) {
        //  if negative, add 1 to complemented LSB
        if (firstNegative) {
            firstDigit++;
        }
        if (secondNegative) {
            secondDigit++;
        }
        myCarry = previousCarry;
    } else {
        myCarry = addNUMBERs(first, firstSize, firstNegative,
            second, secondSize, secondNegative,
            previousCarry);
    }

    /*
        2nd half of the problem.

        Sum the digits and save them in first[].
    */
    mySum = firstDigit + secondDigit + ((myCarry) ? 1 : 0);
    if ((myCarry = (mySum > 9))) {
        mySum -= 10;
    }
    pushSum(mySum + '0');
    return(myCarry);
}

//  Handle the printing logic.
void addAndPrint(char *first, int firstSize, bool firstNegative,
        char *second, int secondSize, bool secondNegative,
        int previousCarry) {

    openSum();
    addNUMBERs(first, firstSize, firstNegative,
        second, secondSize, secondNegative,
        previousCarry)
    closeSum();
    if (*sumPointer<'5') {
        //  it's positive
        for (; *sumPointer=='0'; sumPointer++) {} // discard leading 0s
        //  if all zeros (sumPointer @ NUL), back up one
        sumPointer -= (*sumPointer == NUL) ? 1 : 0;
        printf("%s\n", sumPointer);
    } else {
        //  it's negative
        char    *p;

        //  discard leading 0s (9s in 10s complement)
        for (; *sumPointer=='9' && *sumPointer; sumPointer++) {}
        //  if -1 (sumPointer @ EOS), back up one
        sumPointer -= (*sumPointer == NUL) ? 1 : 0;
        for (p=sumPointer; *p; p++) {
            *p = '0' + ('9' - *p); // uncomplement
            //  special handling, +1 for last digit
            *p += (*(p+1)) ? 0 : 1;
        }
        printf("-%s\n", sumPointer);

    }
    return;
}

/*
    Lex a number from STDIN.

Arguments:
    bufferPointer - pointer to a pointer to a buffer, use as
            **buffer = c;   // put "c" in the buffer
            *buffer += 1;   // increment the buffer pointer
            (*buffer)++;    // also increments the buffer pointer

All sorts of side-effects:
    - getc(stdin)
    - ungetc(...,stdin)
    - modifies value of **bufferPointer
    - modifies value of *bufferPointer

Returns:
    lexNUMBER() - number of bytes added to *bufferPointer,
            *1 if POSITIVENUMBER,
            *-1 if NEGATIVENUMBER
    *bufferPointer - points to the LSB of the number parsed + 1
*/
#define pushc(c) (*((*bufferPointer)++)=c)
bool lexNUMBER(char **bufferPointer) {
    char    c;
    int size = 0;
    bool    sign = false;

    /* lex a NUMBER */
    if ((c=getchar()) == '0') {
        pushc(c);
        c = getchar();
        size++;
    } else {
        if (c == '-') {
            sign = true;
            c = getchar();
            // "-" isn't a digit, don't add to size
        }
        if (c == '0') {
            die();
        }
        for (size=0; isdigit(c); size++) {
            if (size >= MAXDIGITS) {
                die();
            }
            pushc(c);
            c = getchar();
        }
    }
    if (size < 1) {
        die();
    }
    ungetc(c,stdin);        // give back unmatched character
    return (sign);
}

int main() {
    int c;
    char    buffer[MAXVALIDINPUT];
    char    *bufferPointer;
    char    *first, *second;
    int firstSize, secondSize;
    bool    firstNegative, secondNegative;

    bufferPointer = buffer + 1; // hack, space for leading digit
    //  parse 1st number
    first = bufferPointer;
    firstNegative = lexNUMBER(&bufferPointer);
    firstSize = bufferPointer - first;
    *(bufferPointer++) = NUL;   // hack, space for EOS
    bufferPointer++;        // hack, space for leading digit
    //  parse separating blank
    if ((c=getchar()) != ' ') {
        die();
    }
    //  parse 2nd number
    second = bufferPointer;
    secondNegative = lexNUMBER(&bufferPointer);
    secondSize = bufferPointer - second;
    *(bufferPointer++) = NUL;   // hack, space for EOS
    //  parse end of input
    c = getchar();
    if (! ((c == EOF) || ((c == '\n') && ((c=getchar()) == EOF))) ) {
        die();
    }
    //  Some very implementation-specific massaging.
    *(--first) = '0';       // prefix with leading 0
    *(first+(++firstSize)) = NUL;   // add EOS
    *(--second) = '0';      // prefix with leading 0
    *(second+(++secondSize)) = NUL; // add EOS
    //  add and print two arbitrary precision numbers
    addAndPrint(first, firstSize, firstNegative,
        second, secondSize, secondNegative, false);
    return(0);
}

这里有一些测试工具和一些测试用例,可以帮助您入门。随意撕毁过多使用perl。它所开发的系统没有现代化的工具。

#!/bin/bash
#
#   testharness.sh
#
# Use as: bash testharness.sh program_to_be_tested < test_data
#
# Each line in the test data file should be formatted as:
#
#   INPUT = bash printf string, must not contain '"'
#   OUTPUT = perl string, must not contain '"'
#           (inserted into the regex below, use wisely)
#   TESTNAME = string, must not contain '"'
#   GARBAGE = comments or whatever you like
#   INPUTQUOTED = DQUOTE INPUT DQUOTE
#   OUTPUTQUOTED = DQUOTE OUTPUT DQUOTE
#   TESTQUOTED = DQUOTE TESTNAME DQUOTE
#   TESTLINE = INPUTQUOTED *WSP OUTPUTQUOTED *WSP TESTQUOTED GARBAGE
TESTPROGRAM=$1
TMPFILE=testharness.$$
trap "rm $TMPFILE" EXIT
N=0         # line number in the test file
while read -r line; do
    N=$((N+1))
    fields=$(perl -e 'split("\"",$ARGV[0]);print "$#_";' "$line")
    if [[ $fields -lt 5 ]]; then
        echo "skipped@$N"
        continue
    fi
    INPUT=$(perl -e 'split("\"",$ARGV[0]);print "$_[1]";' "$line")
    OUTPUT=$(perl -e 'split("\"",$ARGV[0]);print "$_[3]";' "$line")
    TESTNAME=$(perl -e 'split("\"",$ARGV[0]);print "$_[5]";' "$line")
    printf -- "$INPUT" | $TESTPROGRAM > $TMPFILE
    perl -e "\$t='^\\\s*$OUTPUT\\\s*\$'; exit (<> =~ \$t);" < $TMPFILE
    if [[ $? -ne 0 ]]; then     # perl -e "exit(0==0)" => 1
        echo "ok $TESTNAME"
    else
        echo -n "failed@$N $TESTNAME," \
            "given: \"$INPUT\" expected: \"$OUTPUT\" received: "
        cat $TMPFILE
        echo
    fi
done


一小部分测试用例:

"0 0"       "0" "simple, 0+0=0"
"1 1"       "2" "simple, 1+1=2"

""      "E" "error, no numbers"
"0"     "E" "error, one number"
"0  0"      "E" "error, two/too much white space"
"0 0 "      "E" "error, trailing characters"
"01 0"      "E" "error, leading zeros not allowed"

"-0 0"      "E" "error, negative zero not allowed
"0 -0"      "E" "error, negative zero not allowed here either

"1 1\n"     "2" "LF only allowed trailing character

"\0001 1\n"    "E" "error, try to confuse C string routines #1"
"1\00 1\n"  "E" "error, try to confuse C string routines #2"
"1 \0001\n"    "E" "error, try to confuse C string routines #3"
"1 1\000\n"    "E" "error, try to confuse C string routines #4"
"1 1\n\000"    "E" "error, try to confuse C string routines #5"

"-1 -1"     "-2"    "add all combinations of -1..1 #1"
"-1 0"      "-1"    "add all combinations of -1..1 #2"
"-1 1"      "0" "add all combinations of -1..1 #3"
"0 -1"      "-1"    "add all combinations of -1..1 #4"
"0 0"       "0" "add all combinations of -1..1 #5"
"0 1"       "1" "add all combinations of -1..1 #6"
"1 -1"      "0" "add all combinations of -1..1 #7"
"1 0"       "1" "add all combinations of -1..1 #8"
"1 1"       "2" "add all combinations of -1..1 #9"

"0 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "0+99 digits should work"

"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "99 digits+99 digits should work"

"500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "test for accumulator overflow"

"-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 0" "-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "0+negative 99 digits work"

"-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "-200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "99 digits+99 digits (both negative) should work"

"-500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "-1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "test for negative accumulator overflow"

"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 0" "E" "error, 100 digits"

修复了最后两个大的负数测试。他们没有测试负数。
Scott Leadley 2014年

我从您的代码中收到很多有关-Wall -Wextra的警告。

@Lembik其他张贴者可以随意复制词法分析器并修复编译器警告。它确实实现了安全的词法分析器,并且确实执行了任意精度算术(某种程度上)。我在mal编码上花了一些力气(请参阅代码中的注释),因此您应该收到很多编译器警告。Lexer的金色星星和后部的快速靴子无视其他条件怎么样?
斯科特·利德利

这似乎非常合理:)考虑一下。

1
@Lembick使用10s补码算术替换为所有C解决方案。移动了“不好的例子”解决方案,以使用bc单独的答案。
Scott Leadley 2014年

3

289

编辑:此代码仅适用于正整数。自从我发布此答案以来,规则已经更改。

#include <stdio.h>
#include <stdlib.h>
int r[101],s;void x(int i){r[i]|=32;if(r[i]>41)r[i+1]++,r[i]-=10,x(i+1);}void f(int b){int c=getchar();if(c!=b){if(s>99||c<48||c>57)exit(puts("E"));f(b);r[s]+=c-48;x(s++);}}int main(){f(32);s=0;f(10);for(s=100;s--;)if(r[s])putchar(r[s]+16);return 0;}

取消评论的版本:

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

//global variables are automatically init to zero
int result[101]; //101 because 2 numbers of 100 digits can give a 101-digits result
int currentNumber;

void reportAddition(int i) {
    result[i]|=0x20; //flag "active" value, 6th bit
    if(result[i]>9+0x20) {
        result[i+1]++;
        result[i]-=10;
        reportAddition(i+1);
    }
}

void addNumber(int endingChar) {
    int c=getchar();
    if(c!=endingChar) {
        if(currentNumber>99||c<'0'||c>'9') //error
            exit(puts("Error"));
        addNumber(endingChar);
        result[currentNumber]+=c-'0';
        reportAddition(currentNumber); //handle case when addition give a value greater than 9
        currentNumber++;
    }
}

int main() {

    addNumber(' '); //add first number
    currentNumber=0;
    addNumber('\n'); //add second

    for(currentNumber=100;currentNumber--;)
        if(result[currentNumber])
            putchar(result[currentNumber]+'0'-0x20); //display char
    return 0;
}

您是否拒绝输入超过99位的数字?在我看来,您应该。
约翰·德沃夏克

@JanDvorak,是的。
Michael M.

我收到几个编译警告:./tmp.c: In function ‘f’: ./tmp.c:3:1: warning: suggest parentheses around comparison in operand of ‘|’ [-Wparentheses] ./tmp.c:3:1: warning: suggest parentheses around comparison in operand of ‘|’ [-Wparentheses] ./tmp.c: In function ‘main’: ./tmp.c:3:1: warning: control reaches end of non-void function [-Wreturn-type]
user12205

我并不是要指定数字是正数。道歉。

@ace我没有这个警告在这里,正在取代(s>99|c<48|c>57)(s>99||c<48||c>57)解决呢?
Michael M. 2014年

2

442

它很长,所以我可能在周末进一步打下去。假定输入来自以EOF终止的stdin(无换行符),分隔符仅为ASCII值32的一个字符(即,' '字符)。

#include<stdio.h>
char a[102],b[102],c[102],*p=a,d;int i,j=101,l,L,k,F=1;int main(){while(~(k=getchar())){if(47<k&&k<58){p[i++]=k;if(i==101)goto f;}else if(k==32&&F)p=b,l=i,F=0,i=0;else goto f;}L=i;for(i=(l<L?l:L)-1;i+1;i--){c[j]=(L<l?b[i]-48+a[i+l-L]:a[i]-48+b[i+L-l]);if(c[j--]>57)c[j]++,c[j+1]-=10;}for(i=(L<l?l-L-1:L-l-1);i+1;i--)c[j--]=(L<l?a[i]:b[i]);for(i=0;i<102;i++)if(c[i]&&(c[i]-48||d))d=putchar(c[i]);return 0;f:return puts("E");}

错误消息将是单个字符“ E”,然后是新行。

加上换行符和一些缩进:(以下为可读版本,请随时跳过此处)

#include<stdio.h>
char a[102],b[102],c[102],*p=a,d;
int i,j=101,l,L,k,F=1;
int main(){
    while(~(k=getchar())){
        if(47<k&&k<58){
            p[i++]=k;
            if(i==101)goto f;
        }else if(k==32&&F)p=b,l=i,F=0,i=0;
        else goto f;
    }
    L=i;
    for(i=(l<L?l:L)-1;i+1;i--){
        c[j]=(L<l?b[i]-48+a[i+l-L]:a[i]-48+b[i+L-l]);
        if(c[j--]>57)c[j]++,c[j+1]-=10;
    }
    for(i=(L<l?l-L-1:L-l-1);i+1;i--)c[j--]=(L<l?a[i]:b[i]);
    for(i=0;i<102;i++)if(c[i]&&(c[i]-48||d))d=putchar(c[i]);
    return 0;
    f:return puts("E");
}

可读的版本(对某些语句进行了些微改动,以使其更具可读性,但是它们的作用应该相同):

#include <stdio.h>
char num1[102],num2[102],sum[102]; //globals initialised to 0
char *p=num1;
int outputZero=0, noExtraSpace=1;
int i=0, j=101, len1, len2, ch;
#define min(x,y) (x<y?x:y)
int main(){
    while((ch=getchar())!=-1) { //assumes EOF is -1
        if('0'<=ch && ch<='9') {
            p[i]=ch;
            i++;
            if(i==101) goto fail; //if input too long
        } else if(ch==' ' && noExtraSpace) {
            p=num2;
            len1=i;
            noExtraSpace=0;
            i=0;
        } else goto fail; //invalid character
    }
    len2=i;
    for(i=min(len1, len2)-1; i>=0; i--) {
        //add each digit when both numbers have that digit
        sum[j]=(len2<len1?num2[i]-'0'+num1[i+len1-len2]:num1[i]-'0'+num2[i+len2-len1]);
        if(sum[j]>'9') { //deal with carries
            sum[j-1]++;
            sum[j]-=10;
        }
        j--;
    }
    for(i=(len2<len1?len1-len2-1:len2-len1-1); i>=0; i--) {
        //copy extra digits when one number is longer than the other
        sum[j]=(len2<len1?num1[i]:num2[i]);
        j--;
    }
    for(i=0; i<102; i++) {
        if(sum[i] && (sum[i]-'0' || outputZero)) {
            putchar(sum[i]);
            outputZero=1;
            //if a digit has been output, the remaining zeroes must not be leading
        }
    }
    return 0;
    fail:
    puts("Error");
    return 0;
}

goto fail;是在嘲笑苹果。

我使用的gcc版本是gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3,没有任何警告。


-1 1作为输入呢?

@Lembik打印错误消息,因为输入应为“两个空格分隔的整数”。
user12205 2014年

哦,对不起,我把它弄糟了。我以为我已经改变了。

当前,您的代码始终为我输出E。例如,我尝试了“ 1 1”。还可以让输入来自stdin吗?

@Lembik输入来自stdin(getchar()始终从stdin获取)。假定它是EOF终止的,没有换行符。您可以通过输入[1] [space] [1] [Ctrl + D] [Ctrl + D]或echo -n '1 1' | program
user12205 2014年

0

633字节

满足一半挑战的“坏男孩” C程序。滥用C,会发出很多警告,但可以起作用。任意精度算法实际上是由进行的bc

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define g() getc(stdin)
#define z(c) b[i++]=c,b[i]='\0'
x(){puts("E\n");exit(1);}main(){int c,y=0,i=0;char b[232]="",*h="echo ",*t=" | bc -q | tr -d '\\\\\\012'";strcat(b,h);i=strlen(h);if((c=g())=='0'){z(c);y=1;c=g();}else{if(c=='-'){z(c);c=g();}c!='0'||x();ungetc(c,stdin);for(y=0;isdigit(c=g());y++){z(c);y<99||x();}}y>0||x();c==' '||x();z('+');y=0;if((c=g())=='0'){z(c);y=1;c=g();}else{if(c=='-'){z(c);c=g();}c!='0'||x();do{if(!isdigit(c))break;z(c);y++;y<=99||x();}while(c=g());}y>0||x();strcat(b+i,t);i+=strlen(t);if(!((c==-1)||((c=='\n')&&((c=g())==-1))))x();system(b);}

未缩小版本

/*
Read input from STDIN. The input must conform to VALIDINPUT:

    NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
    POSITIVENUMBER = NONZERODIGIT *98DIGIT
    NEGATIVENUMBER = "-" POSITIVENUMBER
    NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
    VALIDINPUT = NUMBER SP NUMBER *1LF EOF

Check syntax of input. If input is correct, use the shell command
"echo NUMBER+NUMBER | bc -q" to do the arbitrary precision integer arithmetic.

NB, this solution requires that the "normal" bc be 1st in the PATH.


    Fun C language features used:
    - ignore arguments to main()
    - preprocessor macros
    - pointer arithmetic
    - , operator
    - ?: operator
    - do-while loop
    - for loop test does input
    - implicit return/exit
    - short is still a type!
    - ungetc()
    - use int as bool and 0 & 1 as magic numbers
    - implicit type coersion

5/5/14, Stop fighting the syntax graph. Get rid of "positive" flag.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXDIGITS (99)
#define pushc(c) (buffer[index++]=c,buffer[index]='\0')
#define pushs(s) (strcat(buffer+index,s),index+=strlen(s))

int die() { printf("E\n"); exit(1); }

int main () {
    int c;
    /*
    buffer budget:
    5               "echo "
    1+MAXDIGITS (include "-")   NUMBER
    1               "+"
    1+MAXDIGITS (include "-")   NUMBER
    25              " | bc -q | tr -d '\\\012'"
    1               NUL
    */
    char    buffer[5+1+MAXDIGITS+1+1+MAXDIGITS+25+1] = "";
    short   index = 0;
    short   digits;

    pushs("echo ");
    // parse 1st number
    digits = 0;
    if ((c=getchar()) == '0') {
        pushc(c);
        digits = 1;
        c = getchar();
    } else {
        if (c == '-') {
            // "-" doesn't count against digits total
            pushc(c);
            c = getchar();
        }
        (c != '0') || die();
        ungetc(c,stdin);
        for (digits=0; isdigit(c=getchar()); digits++) {
            pushc(c);
            (digits<MAXDIGITS) || die();
        }
    }
    (digits>=1) || die();
    // parse separating blank
    (c == ' ') || die();
    pushc('+');
    // parse 2nd number
    digits = 0;
    if ((c=getchar()) == '0') {
        pushc(c);
        digits = 1;
        c = getchar();
    } else {
        if (c == '-') {
            // "-" doesn't count against digits total
            pushc(c);
            c = getchar();
        }
        (c != '0') || die();
        do {
            if (!isdigit(c)) {
                break;
            }
            pushc(c);
            digits++;
            (digits<=MAXDIGITS) || die();
        } while(c=getchar());
    }
    (digits>=1) || die();
    pushs(" | bc -q | tr -d '\\\\\\012'");
    // parse end of input
    if (! ((c == EOF) || ((c == '\n') && ((c=getchar()) == EOF))) ) {
        die();
    }
    // add two arbitrary precision numbers and print the result to STDOUT
    system(buffer);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.