この問題では、データが読み込まれるファイル名を尋ねる必要があります。また、「def」に答えられた場合は、提供されているデフォルトファイルを使用し、ファイル内の行数を数えます。 次に、データファイルを一度に1行読み込み、wの値を次のように計算します。 -wが 'add'ならx + yを計算します -wが 'sub'ならxyを計算します -ifが ' x 'を計算するx * y - wが' div 'の場合、x/yを計算するファイルからオペレータを読み込み、操作を実行するC++
この結果を一度に1行ずつ画面に出力する。ファイル内のデータの
例:
MULT 4.25 4.56
のdiv 7.64 1.01
のdiv 6.51 2.46
MULT 8.90 6.16
MULT 7.40 8.53
サブ3.05 7.15
サブ9.51 6.16
サブ5.79 1.60
追加5.30 8.87
サブ8.09 1.65
そして、私のコード:私は最初の3つの部分が動作していたが操作を実行するためのwhileループは機能しません。どこが間違っていますか?ありがとう!
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main(){
ifstream input;
string filename;
cout<<"Enter the file name. Enter 'def' to use default file: ";
cin>>filename;
if(filename == "def"){
input.open("M2-P2-data2Read.dat");
}
else{
input.open(filename.c_str());
}
int number_of_lines = 0;
string line;
while (getline(input, line))
++number_of_lines;
cout << "Number of lines in file: " << number_of_lines;
string w;
double x, y;
input >> w;
while(input) {
if(w == "add")
double x, y;
input >> x >> y;
cout << "Solution: " << x+y << endl;
if(w == "sub")
double x, y;
input >> x >> y;
cout << "Solution: " << x-y << endl;
if(w == "mult")
double x, y;
input >> x >> y;
cout << "Solution: " << x*y << endl;
if(w == "div")
double x, y;
input >> x >> y;
cout << "Solution: " << x/y << endl;
input >> w;
}
}
私はそれを逃すためのダムを感じます。しかし、変更した後もまだ動作しません –
@TylerEmmerich、おそらく 'getline'を使ってファイルの内容を読んだり、' input'をファイルの先頭を指し示すように変更したりしないコード行が原因です。 –
それはそれでした!どうもありがとうございます –