使用C将char转换为整数

时间:2016-02-21 14:17:53

标签: c string

我需要创建一个只改变大写或小写字母而不使用函数的程序。

该程序是通过命令行。我试图测试参数,将argv [1]与ASCII表进行比较,但在此之前,我无法使用strtoul将其转换为整数。它总是返回0.代码片段是这样的:

int main (int argc, char** argv){

    char *val;
    char charac;

charac = (char) strtoul (argv[1], &val, 10);

/////charac returns zero here, but it needs to return the ASCII integer value////

if ((charac < 'A') || (charac > 'Z' && charac < 'a') || (charac > 'z'))
    {
      printf ("Invalid character!!\n", charac);
    }
}

我怎么能执行此转换?

3 个答案:

答案 0 :(得分:0)

charac = argv[1][0];
if ((charac >= 'A') && (charac <= 'Z'))
    printf("Lowercased: %c\n", charac - 'A' + 'a');
else if ((charac >= 'a') && (charac <= 'z'))
    printf("Uppercased: %c\n", charac - 'a' + 'A');
else
    print ("Invalid character: %c\n", charac);

答案 1 :(得分:0)

取得here但经过修改很多,包括额外的功能。

#include <stdio.h>

char lower_to_upper(char ch1)
{
      char ch2;

      if(ch1 >= 'a' && ch1 <= 'z'){
            ch2 = ('A' + ch1 - 'a');
            return ch2;
      }
      else{
            ch2 = ch1;
            return ch2;
      }
}

char upper_to_lower (char ch1)
{
      char ch2;

      if(ch1 >= 'A' && ch1 <= 'Z'){
            ch2 = ('a' + ch1 - 'A');
            return ch2;
      }
      else{
            ch2 = ch1;
            return ch2;
      }
}


int main()
{
      char charac, different_case;

      printf("Please input a character: ");
      scanf("%c", &charac);

      if (charac >= 'a' && charac <= 'z')
          different_case = lower_to_upper (charac);
      else if (charac >= 'A' && charac <='Z')
          different_case = upper_to_lower (charac);

      printf("The different case equivalent is: %c\n", different_case);
      return 0;
}

在提到的链接上很好地解释了该算法。

示例输出是:

enter image description here

答案 2 :(得分:0)

这是另一种实现。函数foo()将一个单词(实际上是一个字符数组)作为参数,并在必要时执行大写 - >小写或小写 - >大写转换。

char *foo(char *word){
    char *tmp = word; /* For the new string */
    char *ptr = word; /* To save the poiner */

    for(; *ptr; ++ptr, ++tmp) {
        if (*ptr >= 'a' && *ptr <= 'z')
        /* char is lower case */
            *tmp = (*ptr) - 32;
        else if (*ptr >= 'A' && *ptr <= 'Z')
        /* char is upper case */
            *tmp = (*ptr) + 32;
        else
            *tmp = *ptr;
    }
    return word;
}

int main(int argc, char **argv)
{
    char line[]="This is a test LiNe FOR You";
    char *buf;

    printf("%s\n",foo(strtok(line," ")));

    while(buf=strtok(NULL," "))
        printf("%s\n",foo(buf));

    return 0;
}

以下是上述代码的输出。main()包含strtok()步骤,您可以忽略该问题

$ ./lower_upper
tHIS
IS
A
TEST
lInE
for
yOU