从字符向量中读取有符号数

read signed number from a char vector

我遇到了这个问题,我真的需要帮助,非常感谢: 当我使用 fgets() 输入负数,然后尝试验证用户在 fgets() 读取的字符数组中输入的字符串是否是带有 isdigit() 的数字时,我总是得到正数,有没有办法读取负数。 (我只需要读取数字但可以使用 scanf 因为当它读取一个字符时它让我一团糟)

这是代码的一部分:

char op[30];
int a[30];

int text_ssalto() {
    size_t len = strlen(op);
    fgets(op, sizeof(op), stdin);
    len = strlen(op);
    if (len > 0) {
        op[len - 1] = '[=10=]';
    }

    if (isdigit(*op)) {
        sscanf(op, "%d", &a[x]);
    }

    return 0;
}

我认为您的代码中可能其他地方有问题,这里有一个与您的代码类似的示例,并且可以正常工作。您是否包含正确的 headers?

#include "ctype.h"
#include "stdlib.h"
#include "stdio.h"

int main ()
{
        char op[30];
        fgets(op, sizeof(op), stdin); /* input -11 */
        printf("%s\n", op); /* output -11 */
        if (isdigit(*op)) {
            printf("wrong\n"); // never got printed if input is negative
            sscanf(op, "%d", &a[x]); // read positive number     
        }
        else {
              sscanf(op + 1, "%d", &a[0]); // now a[0] has the positive part
              a[0] = -a[0]; // make it negative if you want.
        }

        return (0);
}
if (isdigit(*op)) {
如果第一个字符是 '-'

将不起作用。

而不是使用

if (isdigit(*op)) {
    sscanf(op, "%d", &a[x]);
}

使用

if ( sscanf(op, "%d", &a[x]) == 1 )
{
   // Got a number.
   // Use it.
}

该函数包含似乎没有必要的无关检查。可以简化为:

int text_ssalto() {
   fgets(op, sizeof(op), stdin);
   if ( sscanf(op, "%d", &a[x]) == 1)
   {
      // Got a number
      // Use it.
   }

   return 0;
}