0

我有以下 C++ 程序:

#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;
}

我使用以下命令编译它:

cl /EHsc switch_suffix.cpp

当我跑步时

switch_suffix py a.exe b.txt

我得到:

a.py
b.py

正如预期的那样。
当我尝试管道时,问题就开始了。运行以下:

dir /B | swich_suffix py 

结果什么都没有,并且正在运行

 dir /B | swich_suffix py 

结果:

not enough arguments!
switch_suffix

系统上的管道工作正常 - 我在其他一些程序上尝试过。
我尝试创建一个 vs 项目并从那里编译代码 - 没有任何帮助。

怎么了,锄头我能修好吗?

我在win7上运行,使用vs2010工具。

4

2 回答 2

3

当你管道时,传递给你的程序的信息在标准输入上,而不是 argv

于 2013-05-20T18:20:27.953 回答
0

当您通过管道传输到另一个程序时,它会进入标准输入,而不是 main 中的参数。

这段代码打印出它收到的内容stdinstdout试试这个:

for (std::string line; std::getline(std::cin, line);) {
      std::cout << line << std::endl;
}
于 2013-05-20T18:24:32.750 回答