为什么我的代码打印两次相同的命令行参数?

时间:2017-02-09 23:47:36

标签: c++ file

我向我的程序传递了三个参数,它们都是文本文件: ARG 1:一个 ARG 2:两个 ARG 3:三个

为什么ARG 1会被打印两次?

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
if(argc < 2)        //check if files exist 1st
{
    cout << "usage: " << argv[0] << " <filename>\n";
}
else        //proceed if files exist
{
    for(int x = 1; x < argc; x++)       //while x < the argument count, read each argument
    {
        ifstream infile;
        infile.open(argv[x]);
        if(!infile.is_open())     //check is file opens
        {
            cout << "Could not open file." << endl;
        }
        else        //if it opens, proceed
        {
            string s;
            while(infile.good())
            {
                infile >> s;        //declare string called s
                if(s[s.length()-1] == ',')      //if the end of the arg string has a ',' replace it with a null
                {
                    s[s.length()-1] = '\0';
                }
                cout << s;
                if(x != (argc -1))
                {
                    cout << ", ";
                }
            }
        }
    }
    cout << endl;
}
return 0;
}

此代码输出:

  

一,二,三

1 个答案:

答案 0 :(得分:1)

您的错误

            cout << s; // here
            if(x != (argc -1))
            {
                cout << ", ";
            }

如何修复

            cout << s;
            s = ""; // fix
            if(x != (argc -1))
            {
                cout << ", ";
            }

您只需将流两次放入 s 字符串即可。就是这样。

用于您目的的简短代码:

    std::ostringstream oss;
    for( std::size_t index = 1; index < argc; ++ index ){
        oss << std::ifstream( argv[ index ] ).rdbuf() ? assert(1==1) : assert(1==0);
    }
    std::cout << oss.str();   

<强>输出

one  
two  
three