使用argv []构建char转换器程序

时间:2013-03-16 13:57:14

标签: c pointers compare command-line-arguments argv

我应该构建一个程序,它采用argv [1]并根据它将字符转换为小写或大写。但是我被卡住了因为C不能将指针与字符串进行比较。关于如何比较的任何想法一个指针和一个字符串,我不想逐个字符地比较它们。 这是代码

 #include <stdio.h>
#include <ctype.h>
#include <string.h>
int main (int argc,char *argv[])
{
    char c;
    if(argc!=2)
    printf("Wrong use of program \n");
    printf("The Format is Lower or Upper \n");
    return -1;
    if ((strcmp(argv[1],"Lower"))==0) 
    {
                          while((c=getchar())!=EOF)
                          {
                                                   printf("-");
                                                   putchar(tolower(c));
                                                   printf("\n");
                                                   } 
                                                   }
    if ((strcmp(argv[1],"Upper"))==0) 
    {
                          while((c=getchar())!=EOF)
                          {
                                                   printf("-");
                                                   putchar(toupper(c));
                                                   printf("\n");
                                                   }
                                                   }
    if ((strcmp(argv[1],"Lower"))!=0 && ((strcmp(argv[1],"Upper"))!=0))
    {
                          printf("Wrong use of program \n");
                          printf("The Format is Lower or Upper \n");
                          return -1;
                          }

                       return 0;
}

2 个答案:

答案 0 :(得分:3)

您要做的是使用strcmp或stricmp函数(不区分大小写)。

答案 1 :(得分:2)

首先,使用strcmp,如果char数组匹配,将返回0。

if (!strcmp(argv[1], "Lower"))
{

其次,如果多个语句适用于if条件,则语句必须包含在{}。

if (argc != 2)
{
   printf("Wrong use of program \n");
   printf("The Format is Lower or Upper \n");
   return -1;
}