2017-02-09 45 views
1

我通过三个参数传递给我的程序,这是所有的文本文件: 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; 
} 

此代码输出:

一个,一个,两个,三个

+2

当您使用** **调试器,这说法导致了问题?变量的值是什么? –

+0

而不是'while(infile.good())',使用'while(infile >> s)'。 –

+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 
+1

谢谢你的答复。我试过你的建议,输出成为:一,二,三 – DoABarrelRoll94

+0

编辑:Nvm,我必须在文本文件 – DoABarrelRoll94

+0

@ DoABarrelRoll94中增加一个额外的空间。如果它解决了您的问题,请批准该帖子。谢谢。 [当有人回答我的问题时,我该怎么办?](http://stackoverflow.com/help/someone-answers) –