getline(cin、input)を使う必要があることがわかりました。私のユーザー入力のために。私は文字列をユーザーからintに変換するためにstringstreamを使用する方法を考え出しました。そのため、数学関数で数値を格納して使用することができます。文字列を関数に渡して整数を返しますか?
例として、ユーザーにStudent IDを尋ねる必要があるとします。そのIDを使って数式を入力する必要があることはまれであり、簡単に文字列として保存できます。しかし、あなたがグレードを求めるのであれば、平均化してGPAに変換する必要があるということは別の話です。
私は基本的に、getlineで数値を入力してからintに変換することをユーザーに求めていますが、変換する必要があるたびに同じ取引を入力する必要はありません。
例:
#include<iostream>
#include<conio.h>
#include<string>
#include<sstream>
using namespace std;
class students{
int s1, s2, s3;
string name, id, input;
public:
void getData(){
cout << "Enter ID: ";
getline(cin, id);
cout << "Enter Name: ";
getline(cin, name);
while(true){
cout << "Enter grades for Math: ";
getline(cin, input);
stringstream convert(input);
if(convert >> s1)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
while(true){
cout << "Enter grades for Science: ";
getline(cin, input);
stringstream convert(input);
if(convert >> s2)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
while(true){
cout << "Enter grades for English: ";
getline(cin, input);
stringstream convert(input);
if(convert >> s3)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
}
void showData(){
cout << "\n" << id << "\t" << name << "\tMath: " << s1 << "\tScience: " << s2 << "\tEnglish: " << s3;
}
};
int main(){
students s[20];
int i, numOfStudents;
string input;
while(true){
cout << "\nNumber of Students? ";
getline(cin, input);
stringstream convert(input);
if(convert >> numOfStudents)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
for(i = 0; i < numOfStudents; i++){
s[i].getData();
}
for(i = 0; i < numOfStudents; i++){
s[i].showData();
}
_getch(); //Only there to keep the command line window open.
return 0;
}
ないあなたが求めているものを確認してください - 関数のシグネチャint型を取って、文字列を返すためにそれをあります? – Steve
これを行うにはいくつかの方法があります。 'std :: istringstream'、' std :: stoi() 'など – user0042