项目场景:
问题描述:
在dev-c++上运行正确 ,在TZOJ出现Presentation Error(答案和标准结果非常接近,在输出结果中,多了或少了不必要的空格或者回车或者其他)的代码
#include<iostream>
using namespace std;
int main()
{
char a[8];
int b,c;
cin.getline(a,8);
cin>>b>>c;
cout<<"name:"<<a<<"\n"<<endl;
cout<<"age:"<<b<<"\n"<<endl;
cout<<"NO:"<<c<<"\n"<<endl;
return 0;
}
在OZJ中问了大佬的代码(暂时还看不懂,用了很多 头文件)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
char a[10];
int b,c;
gets(a);
cin>>b>>c;
cout<<"name:"<<a<<"\n"<<"age:"<<b<<"\n"<<"NO:"<<c<<endl;
return 0;
}
反思:cin用于输入字符串时,只能输入一个字符。
收获:
1.字符串的输入
(1)直接使用cin:接收一个字符串,但遇到“空格”,“回车”,“tab”就结束
#include<iostream>
using namespace std;
int main()
{
char a[8];
cin>>a;
cout<<a<<endl;
}
(2)直接使用string来定义一个字符串:接收一个字符串,但遇到“空格”,“回车”,“tab”就结束
#include<iostream>
using namespace std;
int main()
{
string a;
cin>>a;
cout<<a<<endl;
}
(3)使用cin.getline:可以接受空格并输出。
#include<iostream>
using namespace std;
int main()
{
char a[3];
cin.line(a,3);
cout<<a<<endl;
}
以下参考:
https://blog.csdn.net/u011486738/article/details/82082405
(4)getline(): 接受一个字符串,可以接收空格并输出,需包含“#include”
(5)gets(): 接受一个字符串,可以接收空格并输出,需包含“#include
(6)getchar():接受一个字符,需包含“#include
(7)cin.get:
(a)cin.get(字符变量名)可以用来接收字符
(b)cin.get(字符数组名,接收字符数)用来接收 一行字符串,可以接收空格
(c)cin.get(无参数)没有参数主要是用于舍弃输入流中的不需要的字符,或者舍弃回车,弥补cin.get(字符数组名,接收字符数目)的不足.
2.error:"gets’ was not declared in this scops"
gets()已经不被PAT中C++编译器支持,但是C语音编译器未受影响,把头文件改成C语言格式,用C语音编译器即可通过。
比较详细的解决办法:
https://blog.csdn.net/qq_36525099/article/details/86631881