今天遇到一个题目,要求输入一个字符串,字符串中存在空格,6个数字,输入为一行,并用逗号相隔···,该题目其他都是十分简单的,但是输入却存在一些问题。
乍看之下,这个题目非常简单,但是编了一会就遇到一个问题,c++输入都是以“空格”或者“回车键”为终止符的,因此很难输入一个带空格的字符串。
于是进行了一波查阅,发现C++无非是以下几种输入方式:
1、c语言的输入输出方式,c++也是可以使用的:scanf(),用法类似C,在此不赘述,但是该方法遇到空格就暂定输入了,因此不可行。
2、cin>>,这个是c++特有的输入方式,但是麻烦的是该方法也是遇到空格或者是回车键就结束了。
3、cin.get(),该方法到时好了一些,cin.get()函数可以接收空格,遇回车结束输入。这样一来就成功将空格读入了,但是麻烦的是我没办法在“,”停止输入,这就又带来了下一个问题,于是继续看其他的方法。
给个网上的例子:
int main()
{
char st[50];
cin.get(st,50);
cout<<a<<endl;// 输出也可以用printf("%s",st);
return0;
}
4、getline(cin, str, ‘,’)终于成功解决问题,可以读入带空格的字符串,存在一个字符串变量中,遇到第三个形参的的字符就结束输入。成功读入。
附上成功的代码:
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <cstdlib>
using namespace std;
class Student {
// your code here
private:
//student infomation
int age;
int student_id;
int grades[4]; //this is four years' grades
string student_name;
double ave_grades;
public:
//this function is used to read the data that includes the infomation above
void input()
{
getline(cin, student_name, ',');
scanf("%d,%d,%d,%d,%d,%d", &age, &student_id, &(grades[0]), &(grades[1]), &(grades[2]), &(grades[3]));
}
//this function is used to print the data
void output()
{
int i;
//for(i=0;i<20;i++){
// if (student_name[i] != ','){
cout<<student_name;
//}
//else if (student_name[i] == ','){
// break;
//}
// }
cout<<","<<age<<","<<student_id<<","<<ave_grades;
}
//this function is used to calculate the average grades
void calculate()
{
ave_grades = 1.0*(grades[0]+grades[1]+grades[2]+grades[3])/4;
}
};
int main() {
Student student; //定义类的对象
student.input(); // 输入数据
student.calculate(); // 计算平均成绩
student.output(); // 输出数据
}