【发布时间】:2017-10-24 08:35:28
【问题描述】:
我发现我需要开始使用 getline(cin, input);对于我的用户输入。我想出了如何使用 stringstream 将来自用户的字符串转换为 int,以便我可以在数学函数中存储和使用数字。
例如,假设您需要向用户询问学生 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 并返回一个字符串?
-
有几种方法可以做到这一点。
std::istringstream、std::stoi()等
标签: c++ string int stringstream