[英]How do you read values from a text file in c++?
基本上我必須從讀取的文本文件中獲取 2 個值(學生分數和總分)
97 127
並打印出學生百分比。
這是我的代碼
#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;
}
我的問題是,當我運行程序時,結果是
3608900
當我只要求打印 student_score 值時,它會打印出一個完全不同的數字。
你的錯誤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
筆記
始終將變量初始化為正確的相關類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.