2016-11-24 14 views
0

私はC++を初めて使いましたので、少し慣れていて、それに対処する方法を学びました。 だから私がしようとしているのは、5行のテキストを含むテキストファイルを開くプログラムを書くことです。各行は空白で区切られた5つの整数を持っていて、コンマと実行中の平均が続きます。私は整数の行全体と各行の最初の整数からの実行中の平均値を表示するようにコンソールを管理しました。すべてのヘルプやアドバイスをいただければ幸いです:)C++ Help:入力ファイルから読み込んだ個々の整数と実行中の平均値を表示しようとしています

#include <iostream> 
#include <fstream> 
#include <string> 
#include <stdlib.h> 
using namespace std; 

int main() 
{ 
    string filename; 
    string mystring; 
    double average = 0; 
    double total = 0; 
    int i = 1; 

    cout << "Enter name of file to open: " << endl; 
    cin >> filename; 

    ifstream inputfile; 
    inputfile.open(filename.c_str()); 

    if (!inputfile) 
    { 
    cout << "Error opening file: " << filename << endl; 
    return -1; 
    } 

    while (!inputfile.eof()) 
    { 
    getline(inputfile, mystring); 
    total = atof(mystring.c_str()) + total; 
    average = total/i; 

    cout << mystring << " , " << average << endl; 

    i++; 
    } 

    inputfile.close(); 
} 

答えて

0

ちょうどstd::vector<std::string>にMYSTRING分割する方法を確認するためにSplit a string in C++?をチェックし、その後、1行のすべての項目を反復処理することを、このベクトルを反復処理することができます。

そのような何か:

void split(const std::string &s, char delim, std::vector<std::string> &elems) { 
    std::stringstream ss; 
    ss.str(s); 
    std::string item; 
    while (std::getline(ss, item, delim)) { 
     elems.push_back(item); 
    } 
} 


std::vector<std::string> split(const std::string &s, char delim) { 
    std::vector<std::string> elems; 
    split(s, delim, elems); 
    return elems; 
} 

while (!inputfile.eof()) 
{ 
    getline(inputfile, mystring); 

    std::vector<std::string> items; 
    split(mystring, ' ', items); 
    if (!items.empty()) 
    { 
     for (std::vector<std::string>::iterator iter = items.begin(); iter != items.end(); ++iter) 
     { 
      total = atof(iter->c_str()) + total; 
     } 
     // not clear why you were dividing by i 
     // you may divide by item.size() if you want the average of every items on the line 
     average = total/items.size(); 

     cout << mystring << " , " << average << endl; 

    } 
} 
関連する問題