9.18 C++对C的扩充
使用cout实现输出斐波那契前20项的值
#include <iostream>
using namespace std;
int main()
{
int n1=1,n2=1,n3;
cout << n1 <<" "<< n2<<" ";
for(int i=0;i<18;i++)
{
n3=n1+n2;
cout<<n3<<" " ;
n1=n2;
n2=n3;
}
cout<<endl;
return 0;
}
使用cin和cout完成,提示并输入一个字符,判断该字符是大写还是小写,如果是大写字母,则转变成对应的小写字母输出,如果是小写字母,则转变成对应的大写字母输出,如果是其他字符,则转变成 '*' 并输出
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char ch='0';
cout << "请输入一个字符:" ;
cin>> ch;
if(ch>='a'&&ch<='z')
{
ch=ch-32;
cout<<ch<<endl;
}else if(ch>='A'&&ch<='Z')
{
ch=ch+32;
cout<<ch<<endl;
}else
{
cout<<"*"<<endl;
}
return 0;
}
字符串函数
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
string str;
//判断字符串是否为空
if(str.empty())
{
cout<<"空"<<endl;
}else
{
cout<< "不空"<<endl;
}
//向变量中尾插一写字符
str.push_back('H');
str.push_back('e');
str.push_back('l');
str.push_back('l');
str.push_back('o');
//判断字符串是否为空
if(str.empty())
{
cout<<"空"<<endl;
}else
{
cout << "不空"<<endl;
}
cout<<"字符串长度为:"<<str.size()<<endl;
//cout<<"字符串长度为:"<<strlen(str.c_str())<<endl;
str.pop_back();
cout<<"str = "<<str<<endl; //Hell
str.clear();
cout<<"字符串长度为:"<<str.size()<<endl; //0
return 0;
}