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

时间:2021-03-09 22:49:55

I am supposed to build a program that takes argv[1] and according to it transforms the characters into lower case or upper case.However I am stuck cuz C cant compare a pointer with a string.Any ideas on how to compare a pointer and a string,i dont want to compare them character by character. Here is the code

我应该构建一个程序,它采用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 个解决方案

#1


2  

Firstly, use strcmp which will return 0 if the char arrays match.

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

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

Secondly if more than one statement applies to an if condition, the statements must be encased in {}.

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

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

#2


3  

What you want to do is use the function strcmp or stricmp (for case insensitive).

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

#1


2  

Firstly, use strcmp which will return 0 if the char arrays match.

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

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

Secondly if more than one statement applies to an if condition, the statements must be encased in {}.

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

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

#2


3  

What you want to do is use the function strcmp or stricmp (for case insensitive).

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