How to parse each of the command line parameters?

I have a class which has constructor to parse command line arguments.
I have command line parameters like this:
inputfile.png destfile.png (12,14,35)-(13,16,42)-0000FF (102,104,55)-(103,106,65)-00FFFF

I want to separate each of the arguments which have - or , . using 1) "-" delimiter and then 2) the dash delimiter. This code bellow seems not working. How to fix it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <sstream>
#include <iostream>
#include <cstdio>

MyClass::MyClass(int argc, _TCHAR **argv){
	_TCHAR *a;
	for(int i = 0; i < argc; i++)
	{
		cout << "hello" ;
		a = argv[i];
		std::istringstream ss((_TCHAR) a);
		std::string token;

		while(std::getline(ss, token, ',')) 
		{
			std::cout << token << '\n';
		}

	}
};
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

struct my_class
{
    my_class( int argc, char* argv[] )
    {
        std::vector<std::string> raw_args( argv, argv+argc ) ;
    
        for( std::string str : raw_args )
        {
            std::cout << "raw: " << str << "    parsed: " ;
            for( char& c : str )
                if( c == '(' || c == ')' || c == ',' || c == '-' ) c = ' ' ;
    
            std::istringstream stm(str) ;
            std::string token ;
            while( stm >> token ) std::cout << token << "   " ;
            std::cout << '\n' ;
        }
    }
};


int main( int argc, char* argv[] ) {  my_class( argc, argv ) ; }

http://coliru.stacked-crooked.com/a/6791642c62404538
I think you used syntax for C++ v11 but I use Visual Studio C++ 2010 which does not support that syntax:

for( std::string str : raw_args )

for( char& c : str )

I tried to do it for C++ v03
I have changed the type from _TCHAR to char and now argv contains only first character of the argument. How to correct to get whole argument and to pass it as string to istringstream?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MyGlobalClass::MyGlobalClass(int argc, char* argv[]){
	char *a;
	for(int i = 0; i < argc; i++)
	{
		a = argv[i];
		std::istringstream ss((string) a);
		std::string token;

		while(std::getline(ss, token, '-')) 
		{
			std::cout << token << '\n';
		}

	}
};
Last edited on
I have made it working. Yet I am working on the parsing but I know how to do it already. Thanks for your code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct my_class
{
    my_class( int argc, char* argv[] )
    {
		std::string arg;
        std::vector<std::string> raw_args( argv+1, argv+argc ) ;

		for (std::vector<std::string>::iterator it = raw_args.begin(); it != raw_args.end(); ++it)
        {
			arg=(*it); 
			std::cout << "raw: " + arg + "\n";
        }
    }
};
Last edited on
Topic archived. No new replies allowed.