2

所以我正在尝试制作一个编码/解码程序。到目前为止,我被困在编码部分。我必须能够从命令行参数中获取消息,并使用种子随机数对其进行编码。这个数字将由用户作为第一个参数给出。

我的想法是从 getchar 获取 int 并添加随机数结果。然后我想把它放回标准输出,以便另一个程序可以将它作为参数读取,以使用相同的种子对其进行解码。到目前为止,我无法让 putchar 正常工作。关于我应该解决或关注什么的任何想法?提前致谢!

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

int main(int argc, char *argv[]) { 
    int pin, charin, charout;
    // this verifies that a key was given at for the first argument
    if (atoi(argv[1]) == 0) {
        printf("ERROR, no key was found..");
        return 0;
    } else {
        pin = atoi(argv[1]) % 27; // atoi(argv[1])-> this part should seed the srand
    }    

    while ((getchar()) != EOF) {        
        charin = getchar();        
        charout = charin + pin;        
        putchar(charout);        
    }    
}
4

1 回答 1

3

你不应该调用getchar()两次,它会消耗流中的字符并且你会丢失它们,试试这样

while ((charin = getchar()) != EOF) {
    charout = charin + pin;
    putchar(charout);
}

此外,不要检查是否atoi()返回0数字和有效种子,而是执行此操作

char *endptr;
int pin;
if (argc < 2) {
    fprintf(stderr, "Wrong number of parameters passed\n");
    return -1;
}
/* strtol() is declared in stdlib.h, and you already need to include it */
pin = strtol(argv[1], &endptr, 10);
if (*endptr != '\0') {
    fprintf(stderr, "You must pass an integral value\n");
    return -1;
}
于 2015-10-30T02:50:32.023 回答