C++基础知识学习记录—补充
1、C++新增的赋值语法
#include <iostream>
using namespace std;
int main()
{
//C++新的赋值语法
//1、传统的赋值语法
int a,b;
a=100;
b=99;
//C++新的赋值语法
int c(2);//相当于给c赋值2
int d(c);//相当于把c的值赋值给d
cout << "c=" << c << endl;
cout << "d=" << d << endl;
//C++11新增的赋值语法
int e{1};
int f{e};
cout << "e=" << e << endl;
cout << "f=" << f << endl;
double num=3.14
//{}为一致性初始化,数据窄化赋值时会警告
int nu{num};//编译时添加警告
cout << num << "=====" << nu << endl;
return 0;
}
2、键盘的连续输入和输入带空白的字符串
#include <iostream>
using namespace std;
int main()
{
//键盘输入
//cin进行键盘连续输入 变量之间用空格隔开
// string uname;
// int age;
// cout << "请输入您的 姓名和年龄:";
// cin >> uname >> age;
// cout << "我叫" << uname << "今年" << age << "岁了" << endl;
//也可以输入中间有空格的字符串
string hobbys;
cout << "请输入您的爱好:";
getline(cin,hobbys);
cout << "=================" << endl;
cout << hobbys << endl;
return 0;
}
3、字符串类型string
string是C++新增的字符串类,注意string不是C++的基本数据类型。使用时需要引入头文件#include <string>
string作为新的字符串类型,可以在绝大多数情况下替代原有的字符串表示方式,不必担心字符串长度等问题。
string类内置了一些与字符串相关的函数方便程序员调用(后续补充更多)。
string类支持下标与迭代器(后续讲解)操作。
除了可以使用下标取出字符外,也支持使用at函数取出单字符。
#include <iostream>
//c++中如果需要使用string字符串类型,需要显示引入头文件string
//有时候不引入string头文件,也能使用,因为iostream头文件中隐式引入了string头文件,
//但隐式引入有些情况会出现问题,推荐显示引入string头文件
#include<string>
#include<sstream>
using namespace std;
int main()
{
//定义一个字符串变量
string uname="admin";
cout << uname << endl;
//获取字符串的长度
cout << "字符串的长度为:" << uname.size() << endl;
cout << "字符串的长度为:" << uname.length() << endl;
//访问字符串中的指定字符,有两种方法:通过索引访问或者使用at
cout << uname[4] << endl;
cout << uname.at(4) << endl;
//对比:通过索引和at函数两种访问单个字符的方法
//[]索引方法,效率高 at方法方法更安全
cout << uname[100] << endl; //超出字符串最大索引时,会获取到'\0'空字符
// cout << uname.at(100) << endl;//超出最大索引时,程序会终止执行
cout << "hhhhhhhhh" << endl;
//字符串的遍历
//方法1、利用for循环进行遍历
string s="murphy";
for(int i=0;i<s.size();i++){
cout << s[i] << endl;
}
//方法2、脱离下标进行遍历
for(char c:s){
cout << c << endl;
}
//字符串与数字之间的转换
//可以利用字符串流头文件sstream.h,实字符串与数字之间的转换
//整型转成字符串类型
int count=18;
cout << count << endl;//整型18
stringstream ss; //字符串流
ss << count; //将整型变量的值传入到字符串流
string str = ss.str(); //利用xx.str()将xx转成字符串类型
cout << str << endl;//字符串类型18
//字符串类型转成整型
string words="123456";
istringstream iss(words);
int w;
iss >> w;
cout << w;
return 0;
}