简体   繁体   English

如何在C编程中将整数转换为字符串? (例如0 =>零)

[英]How to turn integers into string in c programming? (eg. 0 => zero)

How to turn integers into string in c programming? 如何在C编程中将整数转换为字符串? (eg. 0 => zero) (例如0 =>零)

Code Example: https://onlinegdb.com/BygYM1L9V 代码示例: https : //onlinegdb.com/BygYM1L9V

#include <stdio.h>
#include <stdbool.h>

int main(int argc, const char * argv[]) {
    int input, number, right_digit;
    bool isNegative = false;

    printf("Insert a number:\n ");
    scanf("%d", &input);
    // if keyed-in number is negative, make it positive, but remember it was negative
    if ( input < 0 ) {
        input = input;
        isNegative = true;
    }

    if (isNegative == true){
        printf("negative ");
    }
    number = 0;

    // reversing the digits of input and store in number
    while ( input ) {
        // adds the last digit of input to value from right
        number = 10 * number + input % 10;
        input /= 10;
    }

    do {
        right_digit = number % 10;
        switch (right_digit) {
                case 0:
                    printf("zero ");
                    break;
                case 1:
                    printf("one ");
                    break;
                case 2:
                    printf("two ");
                    break;
                case 3:
                    printf("three ");
                    break;
                case 4:
                    printf("four ");
                    break;
                case 5:
                    printf("five ");
                    break;
                case 6:
                    printf("six ");
                    break;
                case 7:
                    printf("seven ");
                    break;
                case 8:
                    printf("eight ");
                    break;
                case 9:
                    printf("nine ");
                    break;
                }
            number = number / 10;
    } while (number != 0 );

    printf("\n");
    return 0;
}

Expected result for entering 1230 is one two three zero. 输入1230的预期结果是一二三零。

However, this code provides 123 and omits the 0. How do I turn integers into strings? 但是,此代码提供了123并省略了0。如何将整数转换为字符串?

However, is there a better way of doing it? 但是,还有更好的方法吗? Is there any other method? 还有其他方法吗? C coders, please help C程序员,请帮忙

I'd drop the switch for a look-up table. 我将放弃查找表的开关。 Regarding numbers having to be parsed with % operator "backwards" from ls digit and up, simply store them digit by digit in a separate temporary array to easily re-order them. 关于必须使用%运算符从ls位数开始向后解析的数字,只需将它们逐位存储在单独的临时数组中即可轻松地对其重新排序。

void stringify (unsigned int n)
{
  const char* LOOKUP_TABLE [10] =
  {
    "zero", "one", "two", "three", "four", 
    "five", "six", "seven", "eight", "nine",
  };

  if(n == 0)
  {
    puts(LOOKUP_TABLE[0]);
    return ;
  }

  int numbers[10]={0}; // assuming UINT_MAX = 4.29 billion = 10 digits

  for(int i=0; i<10; i++)
  {
    numbers[10-i-1] = n%10;
    n/=10;
  }

  bool remove_zeroes = true;
  for(int i=0; i<10; i++)
  {
    if(!remove_zeroes || numbers[i]!=0)
    {
      remove_zeroes = false;
      printf("%s ", LOOKUP_TABLE[numbers[i]]);
    }
  }
}

Out of your problem a typo in your code : input = input; 出于您的问题,您的代码中有错别字: input = input; must be input = -input; 必须input = -input;

It is easier to work on the number as a string, example : 将数字作为字符串来处理比较容易,例如:

#include <stdio.h>

int main() {
  printf("Insert a number:\n ");

  char s[32];

  if (fscanf(stdin, "%31s", s) != 1) {
    return -1;
  }

  char * p = s;

  if (*p == '-') {
    printf("negative ");
    p += 1;
  }

  for (;;) {
    switch (*p++) {
    case 0:
    case '\n':
      if ((*s == '-') && (p == (s+2))) {
        puts("missing number");
        return -1;
      }
      putchar('\n');
      return 0;
    case '0':
      printf("zero ");
      break;
    case '1':
      printf("one ");
      break;
    case '2':
      printf("two ");
      break;
    case '3':
      printf("three ");
      break;
    case '4':
      printf("four ");
      break;
    case '5':
      printf("five ");
      break;
    case '6':
      printf("six ");
      break;
    case '7':
      printf("seven ");
      break;
    case '8':
      printf("eight ");
      break;
    case '9':
      printf("nine ");
      break;
    default:
      puts(" invalid number");
      return -1;
    }
  }
}

Compilation and executions : 编译和执行:

/tmp % gcc -pedantic -Wall -Wextra n.c
vxl15036 /tmp % ./a.out
Insert a number:
 0
zero 
vxl15036 /tmp % ./a.out
Insert a number:
 -1
negative one 
vxl15036 /tmp % ./a.out
Insert a number:
 12305
one two three zero five 
vxl15036 /tmp % ./a.out
Insert a number:
 007
zero zero seven 
vxl15036 /tmp % ./a.out
Insert a number:
 -
negative missing number
vxl15036 /tmp % ./a.out
Insert a number:
 a
 invalid number

As you see the number is rewritten as it was enter, 0 at left are not removed and -0 is negative zero 如您所见,该数字将按输入时的样子重写,左侧的0不会被删除,而-0为负零


It can be fun to write one thousand two hundred thirty four for 1234 ;-) 它可以是有趣的写1234为1234 ;-)

I made a small change to your program so that it loops through once before to get the number of digits, and then loops through count times for the switch statement. 我对您的程序进行了小幅更改,以使其在获取数字位数之前先循环一次,然后再循环切换语句的count时间。

#include <stdio.h>
#include <stdbool.h>

int main(int argc, const char * argv[]) {
    int input, number, right_digit;
    bool isNegative = false;

    printf("Insert a number:\n ");
    scanf("%d", &input);
    // if keyed-in number is negative, make it positive, but remember it was negative
    if ( input < 0 ) {
        input = -input;
        isNegative = true;
    }

    if (isNegative == true){
        printf("negative ");
    }

    int count = 0;
    int n = input;
    //count the digits
        while(n != 0)
    {
        n /= 10;
        ++count;
    }

    number = 0;

    // reversing the digits of input and store in number
    while ( input ) {
        // adds the last digit of input to value from right
        number = 10 * number + input % 10;
        input /= 10;
    }

    for(int i = 0; i < count; i++) {
        right_digit = number % 10;
        switch (right_digit) {
                case 0:
                    printf("zero ");
                    break;
                case 1:
                    printf("one ");
                    break;
                case 2:
                    printf("two ");
                    break;
                case 3:
                    printf("three ");
                    break;
                case 4:
                    printf("four ");
                    break;
                case 5:
                    printf("five ");
                    break;
                case 6:
                    printf("six ");
                    break;
                case 7:
                    printf("seven ");
                    break;
                case 8:
                    printf("eight ");
                    break;
                case 9:
                    printf("nine ");
                    break;
                }
            number = number / 10;
    }

    printf("\n");
    return 0;
}

I think you use similar logic as this example integrated into your loop, but when you reverse the number the 0's get treated like leading 0's and are ignored. 我认为您使用与集成到循环中的此示例类似的逻辑,但是当您反转数字时,会将0当作前导0对待,并被忽略。 I didn't make any changes to the inside of the loop so that may need to be cleaned up. 我没有对循环内部进行任何更改,因此可能需要清理。

test input: 测试输入:

12345000

output: 输出:

one two three four five zero zero zero 

暂无
暂无

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

相关问题 如何将多个整数放入 int* 选项卡; 在两个不同的循环中,用 0 分隔,例如。 [1,1,1,0,1,1] 在 VS 2019 中 C - How do I put multiple integers into int* tab; in two different loops separated by 0 eg. [1,1,1,0,1,1] in VS 2019 in C 一种基于字符(例如C中的%)将字符串拆分为数组的有效方法 - Efficent way of breaking a string into an array based on a character eg.% in C? 我如何声明一个 int 类型的输入变量,例如。 输入 x(0 - How can i declare a int type input variable eg. take a input x(0<x<1000) in c? 如何将内存分配应用于计算列表中单词数量的C程序? (例如,malloc,calloc,免费) - How to apply Memory Allocation to a C Program which counts the amount of words in a list? (eg. malloc, calloc, free) 如何使用系统提供的 Clang 和 libc 编译 C 程序,例如。 穆尔? - How to compile C program using Clang and libc other than provided by system, eg. musl? 读取.bin文件的某些部分(例如,从11月23日开始):十六进制为int,char字符串。 C - Reading certain part of a .bin file (eg. from 11th 23rd): hex into int, char string. C C编程:整数序列的和直到零,并输出两个相乘的整数的和 - C Programming: Sum of a sequence of integers until zero and prints the sum of two multiplied integers 在 C 中调用 execv(“/bin/sh”, NULL) 时,如何与子进程通信(例如,通过写入运行命令)? - how can I communicate (eg. run commands via write) with a child process when execv(“/bin/sh”, NULL) was called in C? C编程中的整数数组 - array of integers in c programming C编程-整数和字符 - C programming - integers and characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM