0

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.

elyashiv
  • 3,623
  • 2
  • 29
  • 52

2 Answers2

3

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

KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
0

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;
}
Steve
  • 7,171
  • 2
  • 30
  • 52
  • I tried with `cin.getline` to retrive the data into a `char *`. It didn't work. is there an actuall difference between the two? – elyashiv May 20 '13 at 18:55
  • Yes, std::string is an object for storing strings in C++. The memory is managed for you and there are lots of nice methods built into it. `char*` is a pointer to some chars that you have to manage yourself. I would strongly urge you to use std::string when writing in C++. If you're determined to use `char*` then take a look at http://stackoverflow.com/questions/4023895/how-to-read-string-entered-by-user-in-c – Steve May 20 '13 at 19:05