Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

c++ - 传递到命令行的参数未打印,并且程序无限期循环[Ubuntu / C ++](Arguments passed to the command line not printed and the program loops indefinitely [Ubuntu/C++])

I'm trying to implement a simple command line program that takes three arguments and prints them on the linux terminal

(我正在尝试实现一个简单的命令行程序,该程序需要三个参数并将其打印在linux终端上)

For example:

(例如:)

>c++ exec.cpp

>./a 32 + 32

Should print out contents like this

(应该打印出这样的内容)

32

(32)

+

(+)

32

(32)

But the program is looping indefinitely

(但是程序无限循环)

I've implemented a check for argc Like this

(我已经实现了对argc的检查,就像这样)

if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}

In case the argument count is 3

(如果参数计数为3)

These lines of code should be executed

(这些代码行应执行)

else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}

But as I explained before the program loops indefinitely

(但是正如我在程序无限循环之前解释的那样)

EDIT: Since I was asked to post the entire code here it is

(编辑:因为我被要求在这里发布整个代码)

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>

using namespace std;

int main(int argc,char* argv[]) {
 if(argc!=3) {
    cout << "Exit" << endl;
    return -9999;
    }
else {
    for(int i=0;i<argc;i++){
    cout << argv[i] << endl;
    }
    }
}

EDIT 2: Issue still not solved and I'm worried that if I post another question like this I'll be downvoted to oblivion I really need a solution here and I'm not sure what to do

(编辑2:问题仍然没有解决,我担心如果我发布这样的另一个问题,我将被否决了,我真的需要一个解决方案,我不确定该怎么做)

  ask by Ammar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now with code, that does look okey to me in fact.

(现在有了代码,实际上对我来说确实不错。)

There doesn't seem to be a way to have an endless loop in every case.

(在每种情况下,似乎都没有一种方法可以产生无限循环。)

What happens if you add return(0);

(如果添加return(0);会发生什么?)

to the very end of the main function?

(到主要功能的尽头?)

Main always has to return something and compilers normally either complain or do that on their own hwoever if the propgrammer didn't add it.

(Main总是必须返回某些内容,并且如果程序设计器未添加,编译器通常会自行抱怨或自行执行操作。)

Oh, have you tried the cerr variant instead of cout for your error message?

(哦,您是否为错误消息尝试了cerr而不是cout ?)

Because returning from the main right after, is quite the same as the crash I mentioned.

(因为从右后方返回,与我提到的崩溃完全相同。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...