将负整数转换为字符串时如何处理? [英] How to handle negative integer when converting them to strings?

查看:63
本文介绍了将负整数转换为字符串时如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将整数转换为字符串,无论是负数还是正数.到目前为止,我已经可以使用以下代码将正整数转换为字符串.但不是负面的.我如何正确处理它们以将其转换为字符串.这是我正在使用的代码.

I need to convert integer to a string, be it negative or positive. So far i able to convert positive integers to strings using the following code. But not the negative ones. How can i handle them properly to convert them to strings. Here is the code that i was using.

谢谢

Rajat!

 /*
  * C Program which Converts an Integer to String & vice-versa
*/

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

void tostring(char [], int);


int main()
{
char str[10];
int num, result;

printf("Enter a number: ");
scanf("%d", &num);
tostring(str, num);
printf("Number converted to string: %s\n", str);


return 0;
}

void tostring(char str[], int num)
  {
    int i, rem, len = 0, n;

if(num<0)
{
    n=(-1)*(num);

}
else
{
    n=num;
}
while (n != 0)
{
    len++;
    n /= 10;
}
for (i = 0; i < len; i++)
{
    rem = num % 10;
    num = num / 10;
    str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
   }

推荐答案

在执行其他操作之前,请先查看 n 是否为负.如果是这样,请以符号-开始输出(确保 len 还要比原来多1,并且您的字符串化以后再开始一个字符), n 肯定,然后像以前一样继续进行.

Before doing anything else, see if n is negative. If it is, start the output with the sign - (make sure len is also one more than it would be otherwise, and that your stringification starts one character later), make n positive, and continue as you were doing it before.

这篇关于将负整数转换为字符串时如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆