【问题标题】:C++ return negative stringC++ 返回负字符串
【发布时间】:2013-09-30 01:43:36
【问题描述】:

您好,我有以下代码将字符串整数转换为整数,这些是代码:

#include <stdio.h>
int str_to_int(char* str) {
   int output = 0;
   char* p = str;
   for (int i=0;str[i]!='\0';i++) {
      char c = *p++;
      if (c < '0' || c > '9')
        continue;
      output *= 10;
      output += c - '0';
   }   
   return output;
}

int main(){

    printf("%d\n", str_to_int("456xy"));
    printf("%d\n", str_to_int("32"));
    printf("%d\n", str_to_int("-5"));
    return 0;
}

但是有些如何printf("%d\n", str_to_int("-5")); 有些如何返回 5 而不是 -5,我哪里错了?谢谢

【问题讨论】:

  • 当然返回-5,因为你从不处理'-'字符。最简单的方法:在返回输出前,加上 if(str[0] == '-') reutrn -outout;else return output;
  • @ALan 那么你如何检查x-5
  • @billz,哦,是的,如果 x-5 应该被视为负值,我无法检查。这取决于输入字符串的限制,或者我们可以模拟更复杂的情况,例如“xy--5-6”,并且似乎......我不知道规则...... tks catching。

标签: c++ string algorithm integer


【解决方案1】:

您的代码中似乎根本没有考虑“-”。

你应该插入某种钩子来检测它是否是负值:

#include <stdio.h>
int str_to_int(char* str) {
   int output = 0;
   char* p = str;
   bool isNeg = false;
   if (*p == '-')
   {
       isNeg = true;
       p++;
   }
   for (int i=0;str[i]!='\0';i++) {
      char c = *p++;
      if (c < '0' || c > '9')
        continue;
      output *= 10;
      output += c - '0';
   }   
   if (isNeg)
   {
       output *= -1;
   }
   return output;
}

int main(){

    printf("%d\n", str_to_int("456xy"));
    printf("%d\n", str_to_int("32"));
    printf("%d\n", str_to_int("-5"));
    return 0;
}

【讨论】:

    【解决方案2】:

    if (c &lt; '0' || c &gt; '9') continue; 导致了这个问题。

    当变量 c 为 '-' 时,您只需跳过它。所以你的结果中没有负号。

    请在你的整个逻辑之前测试这个数字是否为负(有'-')。

    【讨论】:

      【解决方案3】:

      在您的转换函数中,您跳过了 - 字符,因为它不在您的测试范围内:

            if (c < '0' || c > '9')
              continue;
      

      要修复它,您需要测试- 字符,并在完成转换后取反。

            if (c < '0' || c > '9') {
              if (c == '-' && no_other_digits_processed_yet) is_neg = true;
              continue;
            }
            //...
      
         if (is_neg) output = -output;
         return output;
      

      【讨论】:

        猜你喜欢
        • 2012-05-03
        • 2021-12-27
        • 2017-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多