/*** 第二章:对象的创建和使用 ***/
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
using namespace std;
int main()
{
// output 13 in the way of octal & hex;
cout << "the octal form is :"
<< oct << 13 << endl;
cout << "the hex form is :"
<< hex << 13 << endl;
// the system can recognize floating-point automatically;
cout << "the float number is:"
<< 3.14159 << endl;
// chang ASCII code 27 to symbol "escape";
cout << "the non-printing character:"
<< char(27) << endl;
// usage of object cin;
int number;
cout << "enter one integer:" << endl;
cin >> number;
cout << "number is:" << dec << number << endl;
// connect the strings with using the "string" class
cout << "Display connenting the strings: " << endl;
string s1,s2; //empty strings;
string s3 = "hello,my ";//initializing;
string s4("name is"); //initializing;
s1 = "Oh!~";
s2 = s3 + s4 + " "; //connect...
s1 += s2; //appending to s1...
cout << s1 + "mumu" << endl;
// copy one file to another with one line at a time;
// we need class <fstream>
ifstream in("chapter2.cpp");// object ifstream opened for reading only;
ofstream out("Cpchapter2.cpp");//object ofstream for writing only;
string temp;
while(getline(in,temp)) //getline() will discard the "\n";
out << temp << "\n";
// copy an entire file into a single string
// object string is dynamic & don't worry about the memory allocation;
string str1,str2;
while(getline(in,str2))
str1 += str2 +"\n";
cout << str1;
// introduction to standard container class -- Vector
// vector class is a template , you can use it in different classes effectively
ifstream in1("chapter2.cpp");
string temp1;
vector<string> v;//make a vector which only loads string objects;
while(getline(in1,temp1))
v.push_back(temp1); // member function adds line to the end of container ;
for(int i=0;i<v.size(); ++i)
cout << i <<":" <<v[i] << endl;
system("pause");
}
/*** 练习感悟 ***/
//向容器中输入元素的正确方式是:
float temp;
cin >> temp;
v.push_back(temp);
// 错误方式是:
cin >> v[i];
// v[i]的使用只用在输出和对元素进行操作(赋值)的时候正确。
//读入回车键的正确方法:
//习题:将一个文件的内容逐行输出,要求当用户按下回车键的时候输出下一行。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream in("chapter2.cpp");
string temp;
char ch;
while(getline(in ,temp))
{
cout << temp;
ch = getchar();
if(ch != '\n')
break;
}
system("pause");
}
//错误方法:cin >> ch; 系统无法识别输入的是'\r' OR '\n'...