简体   繁体   English

将字符串转换为C中的数字

[英]Converting string to number in C

I'm trying to write a program which converts lower cased alphabet to numerical digits. 我正在尝试编写一个将小写字母转换为数字的程序。 a -> 01 b -> 02 ... z -> 26 a-> 01 b-> 02 ... z-> 26

For the first nine letters I need to put a 0 before the number. 对于前9个字母,我需要在数字前加上0。

This is my code. 这是我的代码。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


#define MAXLEN 128

void s2n(char str[])
{

  int i;
  char x;
  char result[256];

  for (i=0; str[i] != '\0'; i++) {
    x = str[i];
    x = x - 96;


    if (x < 10) {

      char src[2] = {0, x};
      strcat(result, src);
    }
    else {
      char src2[1] = {x};
      strcat(result, src2);
    }

    printf("%s",  result);

  }

}

int main(void)
{
  char str[MAXLEN];

  printf("Lower cased string please: ", MAXLEN);
  scanf("%s", str);

  s2n(str);

  return 0;

}

Could you tell me what is wrong with my code?? 你能告诉我我的代码有什么问题吗?

One problem I see is: 我看到的一个问题是:

  char src[2] = {0, x};

You want to use the character 0, rather than the byte value 0 (NUL): 您想使用字符 0,而不是字节值0(NUL):

  char src[2] = {'0', x};

Also, you need to NUL terminate your src array: 另外,您需要NUL终止您的src数组:

  char src[] = {'0', x, 0};

The NUL termination would need to be done in both cases. 在两种情况下都需要终止NUL。

Another problem is your x = x - 96 statement also does not take into account that the character 0 is different from the byte value 0. So 另一个问题是您的x = x - 96语句还没有考虑到字符0与字节值0不同。因此

x = x - 96 + '0';

would be better. 会更好。

You use strcat() on an uninitialized array, result , it doesn't work that way, strcat() looks for the terminating nul byte in it's first parameter, and glues the second parameter from that point. 您在未初始化的数组上使用strcat()result将无法正常工作, strcat()在其第一个参数中查找终止nul字节,然后从该点粘贴第二个参数。

In your case there is no '\\0' in result, calling strcat() with result as the first parameter causes undefined behavior. 在您的情况下,没有结果'\\0' ,调用带有result作为第一个参数的strcat()会导致未定义的行为。

You should at least ensure that there is one '\\0' in result, you can do that by just setting the first element of result to '\\0' , like 您至少应确保结果中有一个'\\0' ,只需将result的第一个元素设置为'\\0' ,例如

result[0] = '\0';

Right before the loop starts, also you pass the second paramter src which is an array but is not a string, because it has no terminating '\\0' , but you actually don't need an array nor strcat() . 就在循环开始之前,您还要传递第二个参数src ,它是一个数组但不是字符串,因为它没有终止符'\\0' ,但是实际上不需要数组或strcat()

You can use an index variable and just assing the i th element of the array to the actual character computed from the original value, like 您可以使用索引变量,并将数组的第i个元素与根据原始值计算出的实际字符相关联,例如

result[i] = x;

Then you don't nul terminate result , which causes undefined behavior when you try to print resutl . 然后,你不nul终止result ,当您尝试打印导致未定义行为resutl

You also passing a parameter to printf() where it's not expecting one, that indicates that you are either silencing or ignoring compiler warnings. 您还将参数传递给不需要的printf() ,这表明您正在沉默或忽略编译器警告。

There are many problems in your code, the following code, does what you want 您的代码中有很多问题,以下代码可以满足您的要求

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void s2n(char chr)
{
    char result[4];
    if (snprintf(result, sizeof(result), "%02d", 1 + chr - 'a') >= sizeof(result))
        return;
    printf("%s",  result);
}

int main(void)
{
    char chr;

    printf("Lower cased string please: ");
    if (scanf(" %c", &chr) != 1)
    {
        fprintf(stderr, "input error!\n");
        return -1;
    }
    s2n(chr);

    return 0;
}

note that no strings are required except the one where you are going to store the result, which you can build easily with sprintf() . 请注意,除了要用于存储结果的字符串外,不需要其他任何字符串,可以使用sprintf()轻松构建该字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM