本文学习自 狄泰软件学院 唐佐林老师的 C++课程
实验1:利用C++标准库 使用String类,排序,连接
实验2:C++标准库使用 – 字符串和数字的转换初探
实验3:C++标准库使用 – 字符串和数字的转换,‘>>’操作符和‘<<’ 操作符返回值
实验4:优化
实验1:利用C++标准库 使用String类,排序,连接
#include <iostream>
#include <string>
using namespace std;
void string_sort(string a[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
/* C++ 标准库中重载了 大于小于的操作符,比较字符串首字符的大小
按照首字符排序
*/
if( a[i] > a[j] )
{
swap(a[i], a[j]);
}
}
}
}
string string_add(string a[], int len)
{
string ret = "";
/* C++ 标准库中重载了 +,+= 操作符, 连接字符串
连接字符串
*/
for(int i=0; i<len; i++)
{
ret += a[i] + "; ";
}
return ret;
}
int main()
{
string sa[7] =
{
"Hello World",
"D.T.Software",
"C#",
"Java",
"C++",
"Python",
"TypeScript"
};
string_sort(sa, 7);
for(int i=0; i<7; i++)
{
cout << sa[i] << endl;
}
cout << endl;
cout << string_add(sa, 7) << endl;
return 0;
}
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ g++ 33-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
C#
C++
D.T.Software
Hello World
Java
Python
TypeScript
C#; C++; D.T.Software; Hello World; Java; Python; TypeScript;
mhr@ubuntu:~/work/c++$
实验2:C++标准库使用 – 字符串和数字的转换初探
实验3:C++标准库使用 – 字符串和数字的转换,‘>>’操作符和‘<<’ 操作符返回值
‘>>’操作符 返回 bool 类型
‘<<’ 操作符 返回 左操作对象本身
if( iss >> num) : 成功返回ture
oss << 543 << “.” << 21
oss << 543 成功后返回 oss —> oss << “.” << 21 --> oss << 21 —>oss : 542.21
实验4:优化
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//直接调用构造函数 产生一个字符串输入流的临时对象,然后将对象内容传输到 n 中
#define TO_NUMBER(s, n) (istringstream(s) >> n)
//ostringstream& 类型转换,暂时不懂为什么 ostringstream() << n 返回的不是 ostringstream类型
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())
int main()
{
double n = 0;
if( TO_NUMBER("234.567", n) )
{
cout << n << endl;
}
string s = TO_STRING(12345);
cout << s << endl;
return 0;
}
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ g++ 33-2.cpp
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ ./a.out
234.567
12345
mhr@ubuntu:~/work/c++$