简体   繁体   English

检测字符串中的负整数

[英]detecting negative integer in a string

Say I take in a string of input and I wanted to check if the user entered a negative number. 假设我输入了一个输入字符串,并且想检查用户是否输入了负数。

bool isNegative(string input[]) {
    int i = 0;
    if (input[i] == "-") {
        return true;
    } else {
        return false;
    }
}

I tried a boolean function to check if the first character is a - sign, representing negative numbers eg -5, -25. 我尝试了一个布尔函数来检查第一个字符是否为-符号,表示负数,例如-5,-25。

However, my Netbeans gave me this error: main.cpp:39:25: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] 但是,我的Netbeans给了我这个错误:main.cpp:39:25:错误:ISO C ++禁止比较指针和整数[-fpermissive]

anyone knows what this means? 有人知道这意味着什么吗?

There are two problems with your code: 您的代码有两个问题:

  • You declare i that never changes. 您声明i永远不会改变。 This is the same as doing input[0] 这与input[0]
  • You compare a character to a string. 您将字符与字符串进行比较。 Instead of "0" (double quotes) you need '0' (single quotes). 代替"0" (双引号),您需要使用'0' (单引号)。

Fixing these two problems will fix your code. 解决这两个问题将解决您的代码。

Note: You can write this function in a single line: 注意:您可以在一行中编写此函数:

bool isNegative(string input) {
    return input[0] == '-';
}

您需要使用单引号表示单个字符,而不是使用双引号表示字符串。

if (input[i] == '-')

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

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