Reputation: 115
So, I'm in the process of writing a program that takes 3 inputs, -r, -u, and -l. Each input makes the program do a certain function. -r runs the rot_13 function, -u runs the convert_all_upper function, and -l runs the convert_all function. However, when I run the program and type -r, all I get is the banana$ in Unix. Any ideas as to what I'm over looking here?
#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;
}
Upvotes: 0
Views: 119
Reputation: 206567
The line
if (answer == "-r")
doesn't do what you expect it to. It just compares two pointers, not the strings.
Change
if (answer == "-r")
to
if ( strcmp(answer, "-r") == 0 )
and
else if (answer == "-u")
to
else if ( strcmp(answer, "-u") == 0 )
Make sure to add
#include <string.h>
PS
If you are using gcc, you can turn on the flag -Wall
to get very useful warnings:
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")
Upvotes: 2