2017-02-06 15 views
-2

は基本的に私はC++のテキストファイルからどのように値を読み込みますか?

97 127 

を読み取って、学生の割合をプリントアウトし、テキストファイルから2つの値(学生はスコアとポイントの合計額)を取らなければなりません。

これは私の問題は、私はプログラムを実行すると値が、私はちょうどそれが印刷さstudent_score値をプリントアウトするように依頼する場合

3608900 

こととして出てくるということです

#include <iostream> 
    #include <fstream> 
    #include <string> 
    #include <cmath> 
    using namespace std; 

    int main() 
    { 
     int student_score; 
     int total_points; 
     int final_score; 

     ifstream inFile; 
     inFile.open("myData.txt"); 

     inFile >> student_score >> total_points; 

     final_score = (student_score/total_points) * 100; 

     cout << final_score; 

     inFile.close(); 
     return 0; 
    } 

私のコードです完全に異なる数字を出す。

+3

には、変数を初期化しますが、そこから読み込みを開始する前に、必ずファイルが実際に開かれたかどうかを確認します。 – NathanOliver

+2

似たような質問と回答がたくさんあります。インターネットで "stackoverflow C++ read file integer"を検索します。 –

+4

さらに、 'student_score/total_points'は、整数除算のために、あなたのケースでは' 0'を返します。 –

答えて

0

バグ
int total_points;

あなたは、単にint/intを分割し、実際にあなたがこれを行うにしてみてください。97/127ので、出力は0です。ここ

何を書くべき

int student_score = 0; 
    float total_points = 0.0; 
    int final_score = 0; 

    std::ifstream inFile; 
    inFile.open("myData.txt"); 

    if(inFile){ 
    inFile >> student_score >> total_points; 
    } else { 
     std::cout << "your-error-code"; 
    } 

    final_score = (student_score/total_points) * 100; 

    std::cout << final_score; 

    inFile.close(); 
    return 0; 

出力

76


NOTE

は常に正しい関連タイプ

関連する問題