为什么这个程序在运行时会崩溃?

时间:2015-02-02 06:02:57

标签: c user-input

所以,我正在编写一个带有3个输入的程序,-r,-u和-l。 每个输入使程序执行某项功能。 -r运行rot_13函数,-u运行convert_all_upper函数,-l运行convert_all函数。但是,当我运行程序并输入-r时,我得到的只是Unix中的banana $。关于我在这里看到什么的任何想法?

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


FILE *
input_from_args(int argc, const char *argv[])
{
    if (argc == 1){
        return stdin;
    }
    else {
        return fopen(argv[1], "r");
    }
}

void
rot_13(FILE *src, FILE *dest)
{
    int c,j;

    while ((c = getc(src)) != EOF)
    {
    if(c>= 'A' && c <= 'Z')
    {
        if((j = c + 13) <= 'Z') 
            c = j;
        else
        {
            j = c - 13;
            c = j;
        }
    }
    else if(c >= 'a' && c <= 'z')
    {
        if((j = c + 13) <= 'z')
            c = j;
        else
        {
            j = c - 13;
            c = j;
        }
    }
    else
    c = c;

    fprintf(dest, "%c", c);
    }
}

void
convert_all_upper(FILE *src, FILE *dest)
{
    int c;

    while ((c = fgetc(src)) != EOF) 
    {
        fprintf(dest, "%c", toupper(c));
    }
}

void
convert_all_lower(FILE *src, FILE *dest)
{
    int c;

    while ((c = fgetc(src)) != EOF) 
    {
        fprintf(dest, "%c", tolower(c));
    }
}


int
main(int argc, const char *argv[])
{

    char answer[4];

    FILE *src = input_from_args(argc, argv);
    FILE *dest = stdout;

    printf("Please enter which conversion -r -u -l\n"); 
    scanf("%s", answer);        


    if (src == NULL)
    {
        fprintf(stderr, "%s: unable to open %s\n", argv [0], argv[1]);
        exit(EXIT_FAILURE);
    }

    if (answer == "-r")
    { 
        rot_13(src, dest);
    }   

    else if (answer == "-u")
    {
        convert_all_upper(src, dest);
    }           
    fclose(src);

    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:2)

该行

if (answer == "-r")

不符合您的预期。它只是比较两个指针,而不是字符串。

更改

if (answer == "-r")

if ( strcmp(answer, "-r") == 0 )

else if (answer == "-u")

else if ( strcmp(answer, "-u") == 0 )

确保添加

#include <string.h>

<强> PS

如果您使用的是gcc,则可以打开标记-Wall以获得非常有用的警告:

test-503.c: In function ‘main’:
test-503.c:88:15: warning: comparison with string literal results in unspecified behavior [-Waddress]
    if (answer == "-r")
               ^
test-503.c:93:20: warning: comparison with string literal results in unspecified behavior [-Waddress]
    else if (answer == "-u")