ページ 11

while文とsystemの組合せ

Posted: 2015年12月03日(木) 15:16
by コハク
ifstream ifs("ls_data.txt");
string str;
char buff[200];
int count=0;
while(getline(ifs,str)){
sprintf(buff,"g++ point.cpp & ./a data/%s data_tra.txt data_tra_check.txt",str.c_str());
system(buff);
Sleep(2000);
cout<<count<<" "<<str.c_str()<<endl;
count++;
if(count==10){break;}
}

dataというサブディレクトリの中にあるファイル名をls_data.txtに書き出してあり, その名前をひとつづつ読み込み, point.cppというプログラムに入力し,
data_tra.txtにその結果を出力, data_tra_check.txtに読み込んだファイル名を書きだしています.

ところが, ファイルの読み込みが終了したのにも関わらず, while文が終了せず, countは0, 1, 2, …, 9, 0, 1, 2, ...,9, 0,...と繰り返します.
system(buff)を消したところ, while文は正常に終了することができました.
while文とsystem関数は同時に用いることができないのでしょうか, 良い方法があったら教えて欲しいです.

Re: while文とsystemの組合せ

Posted: 2015年12月03日(木) 16:14
by かずま
cygwin 上で実行していますね。

system() の中の "g++ point.cpp & ./a ..." の & を ; に変更する。

さらに、この system() を含むプログラムの実行ファイル名を
a.exe から別のもの、例えば b.exe に変更し、./b で起動する。

これでどうなるでしょうか?

point.cpp を毎回コンパイルするのは無駄な気がします。

Re: while文とsystemの組合せ

Posted: 2015年12月03日(木) 16:31
by コハク
ありがとうございます!
&を;に直したところループの重複がなくなりました.

>cygwin 上で実行していますね。
はいcygwinで実行しています

>point.cpp を毎回コンパイルするのは無駄な気がします。
その通りでした. 実行時間を短くするためにもwhile文から出そうと思います.

Re: while文とsystemの組合せ

Posted: 2015年12月03日(木) 18:20
by Dixq (管理人)
上のフォーラムルールにある通り、ソースコードはcodeタグで囲んでくださいね。

Re: while文とsystemの組合せ

Posted: 2015年12月03日(木) 18:47
by コハク
すみません.次からは気をつけます.

コード:

ifstream ifs("ls_data.txt"); 
string str;
char buff[200];
int count=0;
while(getline(ifs,str)){
sprintf(buff,"g++ point.cpp & ./a data/%s data_tra.txt data_tra_check.txt",str.c_str());
system(buff);
Sleep(2000);
cout<<count<<" "<<str.c_str()<<endl;
count++;
if(count==10){break;}
}
一応再掲します.