Question

I have the following c++ program:

#include <iostream>
using namespace std;

//will find the last dot and return it's location
char * suffix_location(char *);

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cout << "not enough arguments!" << endl;
        for (int i = 0; i < argc; i++)
            cout << argv[i] <<endl;
        exit(1);
    }
    //ignore first parameter (program name).
    argv ++;
    argc --;

    //the new suffix
    char * new_suffix = argv[0];

    argv++;
    argc--;

    for (int i = 0; i < argc; i++)
    {
        char * a = suffix_location(argv[i]);
        if (a != NULL)
        {
            a[0] = NULL;
            cout << argv[i] << '.' << new_suffix << endl;
        }
    }
    return 0;
}

char * suffix_location(char * file_name)
{
    char * ret = NULL;
    for (; * file_name; file_name++)
        if (*file_name == '.')
            ret = file_name;
    return ret;
}

I compiled it using the following command:

cl /EHsc switch_suffix.cpp

when I run

switch_suffix py a.exe b.txt

I get:

a.py
b.py

as expected.
the promblem start when I try to pipe. running the following:

dir /B | swich_suffix py 

results nothing, and running

 dir /B | swich_suffix py 

results:

not enough arguments!
switch_suffix

The piping on the system works fine - I tried it on a few other programs.
I tried creating a vs project and compiling the code from there - helped nothing.

whats wrong, and hoe can I fix it?

I'm running on win7, using vs2010 tools.

Was it helpful?

Solution 2

When you pipe to another program it goes to the standard input and not to the arguments in main.

This piece of code prints out what it receives on stdin to stdout, try this:

for (std::string line; std::getline(std::cin, line);) {
      std::cout << line << std::endl;
}

OTHER TIPS

when you pipe, the information that gets passed to your program is on stdin, not argv

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top