标签:ons iostream 声明 cout ring double limit poi int
1、STL<sstream>库:使用string代替字符数组,避免缓冲区溢出;传入参数和返回值类型可自动推导出来,避免类型转换错误
istream、ostream、stringstream分别进行流的输入、输出和输入输出操作;stringstream构造和析构函数耗CPU时间,最好重复使用,clear()清除
string s = "100000";
int n = 0;
stream << s;
stream >> n; // n等于100000.
template <class T> void to_string(string &res, const T &t) { ostringstream oss; oss << t; res = oss.str(); }
sstream库中getline()函数
istream& getline (char* s, streamsize n ); istream& getline (char* s, streamsize n, char delim );
Extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character). 抽取输入,存储为const string,直到所抽取的字符被分隔,如‘\n’,或者已有n个字符被存储(包括‘\0‘)。
1 #include<iostream> 2 #include<sstream> 3 using namespace std; 4 5 // main function 6 int main() { 7 stringstream ss_stream; 8 int first, second; 9 ss_stream << "456"; 10 ss_stream >> first; 11 cout << first << endl; 12 // 注意clear()清除管道已有数据 13 ss_stream.clear(); 14 ss_stream << true; 15 ss_stream >> second; 16 cout << second << endl; 17 18 ss_stream.clear(); 19 ss_stream << "字符串一" << endl; 20 ss_stream << "字符串二" << endl; 21 ss_stream << "字符串三" << endl; 22 ss_stream << "字符串四" << endl; 23 24 // char buffer[100]; // 声明未初始化 25 // while (ss_stream.getline(buffer, sizeof(buffer))) { 26 // printf("msg=%s\n", buffer); 27 // } 28 29 string stemp; 30 while (getline(ss_stream, stemp)) { 31 cout << stemp << endl; 32 } 33 return 0; 34 }
2、C++类模板 template <class T>
模板是泛型编程的基础,类是对象的抽象,模板是类的抽象,用模板能定义出具体类。属于编译时的多态,体现在参数的多态。
使用:template <class T> // 带参数T的类模板
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 // the declaration of class template 6 template<class T> 7 class Point { 8 public: 9 Point(T = 0, T = 0); // 类的构造函数 10 Point(Point&); // 类的拷贝构造函数 11 T Distance(Point&); // 返回类型T的成员函数 12 private: 13 T x, y; 14 }; 15 16 // The implementation of class template Point 17 template <class T> 18 Point<T>::Point(T a, T b) : x(a), y(b){} 19 20 template <class T> 21 Point<T>::Point(Point& a) { 22 x = a.x; 23 y = a.y; 24 } 25 26 template <class T> 27 T Point<T>::Distance(Point &a) { 28 return sqrt((x - a.x)*(x - a.x) + (y - a.y) * (y - a.y)); 29 } 30 31 // main function 32 int main() { 33 Point<int> a1(3, 4), a2(5, 6); 34 cout << "The distance of these two points: "<< a1.Distance(a2) << endl; 35 36 Point<double> b1(7.8, 9.8), b2(34.8, 25.4); 37 cout << "The distance of these two points: "<< b1.Distance(b2) << endl; 38 return 0; 39 }
3、cmath是c++语言中的库函数,其中的c表示函数是来自c标准库的函数,math为数学常用库函数。编译时必须加上参数「-lm」。
标签:ons iostream 声明 cout ring double limit poi int
原文地址:https://www.cnblogs.com/li-ling/p/8911849.html