プログラムに3つの引数を渡しました。これらはすべてテキストファイルです。ARG1:1つのARG 2:2つのARG 3:3
ARG 1が2回印刷されるのはなぜですか?
#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、1、2、3
あなたのバグ
cout << s; // here
if(x != (argc -1))
{
cout << ", ";
}
直し方
cout << s;
s = ""; // fix
if(x != (argc -1))
{
cout << ", ";
}
ストリームをs文字列に2回入れるだけです。それでおしまい。
あなたの目的のためのショートコード:
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加