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

Why does this program crash when I run it?

所以,我正在编写一个接受 3 个输入的程序,-r、-u 和 -l。 每个输入都使程序执行特定功能。 -r 运行s rot_13 函数,-u 运行s convert_all_upper 函数,-l 运行s 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;
}

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")