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

Why is my code printing the same command line arguments twice?

本文关键字:打印 参数 命令行 两次 代码 我的 为什么      更新时间:2023-10-16

我向我的程序传递了三个参数,它们都是文本文件:ARG 1:1ARG 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] = '';
                }
                cout << s;
                if(x != (argc -1))
                {
                    cout << ", ";
                }
            }
        }
    }
    cout << endl;
}
return 0;
}

此代码输出:

一、

一、二、三

你的错误

            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