我如何使该程序从命令行使用多个参数?

问题描述 投票:0回答:1

我有一个接受c字符串并将其反转的程序,但是该c字符串应该从命令行获取,并且我需要它能够容纳多个字符串。

#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;

int main(int argc, char *argv[])
{
    char* str = new char[100];
    str = argv[1];
    for(int i=0; i<=( strlen(str) )/2; i++ )
    {
        char* head = &str[0+i];
        char* tail = &str[(strlen(str)-1-i)];
        char holder=*head;
        *head = *tail;
        *tail = holder;
    }
    cout<<str<<endl;
    return 0;
}

[其他类似Python的语言允许您通过将argv参数更改为argv[1:]来执行此操作,以便从第一个参数开始获取所有内容。我基本上只需要那个。

c++ c-strings argv
1个回答
0
投票

只需将您的代码包装在通过每个命令行参数的循环内即可。

#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;

int main(int argc, char *argv[])
{
    for (int j = 0; j < argc; ++j) {
        char* str = new char[100];
        str = argv[j];
        for(int i=0; i<=( strlen(str) )/2; i++ )
        {
            char* head = &str[0+i];
            char* tail = &str[(strlen(str)-1-i)];
            char holder=*head;
            *head = *tail;
            *tail = holder;
        }
        cout<<str<<endl;
        delete [] str;
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.