C中的getopt总是返回1或' \ 001'对于每一个论点

时间:2016-06-18 00:50:54

标签: c getopt

我正在尝试在我的代码中使用C中的函数getopt(),但它总是返回1。

我完全不知道发生了什么。 最后,我将我的代码缩短为这样的测试:

#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char** argv) {
    int ch;
    while (ch = getopt(argc, argv, "s:E:") != -1) {
        printf(" %d\n", ch);
    }
}

然后我用./test -s 0 -E 1运行它,我得到两个1。 我想我应该至少得到一个69的E或什么的s?

以下是我如何编译它,运行它以及如何使用gdb将命令行传递给它的屏幕截图。

result

首先,我使用了一个&#39; char ch&#39;而不是&#39; int ch&#39;。那时候,我会得到ch =&#39; / 001&#39;来自getopt。

修改

现在有效,它需要括号。 谢谢大家!

2 个答案:

答案 0 :(得分:4)

ch = something != -1

is equivalent to

ch = (something != -1)

因此,你实际上并没有在getopt中得到ch调用的结果,而是得到比较的结果(当循环体被执行时这是真的,因此{{1} })。

要解决此问题,请添加一对额外的括号:

1

答案 1 :(得分:2)

waiting
about toupload
found element
Traceback (most recent call last):
  File "C:\Users\Brian\Desktop\Empire_fort\Bots\GetPICtures\nowupload.py", line 55, in <module>
    image.send_keys(r'C:\Users\Brian\Desktop\Empire_fort\Bots\GetPICtures\Empire.jpg')
  File "C:\Python2.7.11\lib\site-packages\selenium\webdriver\remote\webelement.py", line 321, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)})
  File "C:\Python2.7.11\lib\site-packages\selenium\webdriver\remote\webelement.py", line 456, in _execute
    return self._parent.execute(command, params)
  File "C:\Python2.7.11\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "C:\Python2.7.11\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
Stacktrace:
    at fxdriver.preconditions.visible (file:///c:/users/brian/appdata/local/temp/tmpxjigan/extensions/fxdriver@googlecode.com/components/command-processor.js:10092)
    at DelayedCommand.prototype.checkPreconditions_ (file:///c:/users/brian/appdata/local/temp/tmpxjigan/extensions/fxdriver@googlecode.com/components/command-processor.js:12644)
    at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/brian/appdata/local/temp/tmpxjigan/extensions/fxdriver@googlecode.com/components/command-processor.js:12661)
    at DelayedCommand.prototype.executeInternal_ (file:///c:/users/brian/appdata/local/temp/tmpxjigan/extensions/fxdriver@googlecode.com/components/command-processor.js:12666)
    at DelayedCommand.prototype.execute/< (file:///c:/users/brian/appdata/local/temp/tmpxjigan/extensions/fxdriver@googlecode.com/components/command-processor.js:12608)

解析为:

while (ch = getopt(argc, argv, "s:E:") != -1)

即。比较while (ch = (getopt(argc, argv, "s:E:") != -1)) 的结果并将比较结果(1或0)存储在getopt中。

使用括号覆盖操作顺序:

ch