在最后摆脱额外的空白

时间:2015-07-15 21:15:20

标签: c++

我应该接受命令行输入并以相反的顺序输出它们。我到目前为止的代码是

#include<iostream>
#include<fstream>
using namespace std;

int main(int argc, char *argv[]) {
    for(int num = argc; num >= 2; num--)
        cout << argv[num - 1] << " ";
    for(int num = argc; num < 2; num--)
        cout << argv[num - 1];
    return 0
}

它完成了它的工作,但我在最后一个输出结束时得到了一个不需要的空格,例如,如果我这样做了

./反向第一个第二个第三个

输出

third_second_first _

第一个之后的空间是不受欢迎的,我很难摆脱它。它应该采取与我一样多的论点。有没有一种简单的方法可以删除最后一个空格?

2 个答案:

答案 0 :(得分:1)

删除它的最佳方法是首先不打印它。

测试以确保您至少有一个可打印输入并打印它。然后,对于所有剩余的输入,打印出分隔符,然后输入。

#include<iostream>

int main(int argc, char *argv[]) {
    if (argc > 1)
    {  // Ensure that where is at least one argument to print
        std::cout << argv[argc - 1]; // print last argument without adornment
        for(int num = argc - 2; num > 0; num--)
        { // Print a space and all remaining arguments. 
          // For visibility, I've replaced the space with an underscore 
            std::cout << "_" << argv[num] ;
        }
    }
/* unsure what this loop is supposed to do. Doesn't do anything in it's current state, 
   so I've commented it out.
    for(int num = argc; num < 2; num--) 
    {
        std::cout << argv[num - 1];
    }
*/
    return 0;
}

输入:

first second third

输出:

third_second_first

答案 1 :(得分:-1)

对于“简单”的解决方案,我会做这样的事情:

#include <iostream>

int main(int argc, char* argv[])
{
    while (--argc > 0)
        std::cout << argv[argc] << ' ';
    std::cout << '\n':
}

请注意它会在最后一个(第一个)参数之后打印尾随空格,但除非你的教授要求不具备它,或者你有一个在线评判或类似的东西不允许它,我不知道如何这真的很重要。虽然很容易解决:

while (--argc > 1)
    std::cout << argv[argc] << ' ';
std::cout << argv[argc] << '\n':
相关问题