C++ Primer 学习笔记(一)

书是第四版,人民邮电出版社出版的。感兴趣的朋友可以一同交流下。希望能坚持下去!

===================================================================

命名空间:

在C++语言中,唯一使用完整的命名空间前缀(eg: std::)的情况是在头文件中发生的,例如cout写作std::cout,这是为了不使同一个using声明出现在多个同时引用这个头文件的源文件中。

好的编程习惯是只在头文件中添加必要的内容。

《C++ primer》第四版原文:

There is one casein which we should always use the fully qualified library names: inside headerfiles. The reason is that the contents of a header are copied into our programtext by the preprocessor. When we #include a file, it is as if the exact textof the header is part of our file. If we place a using declaration within aheader, it is equivalent to placing the same using declaration in every programthat includes the header whether that program wants the using declaration ornot.

Ingeneral, it is good practice for headers to define only what is strictlynecessary.

===================================================================

String类型:

getline()与<<的区别:

getline函数有两个参数,第一个是输入流对象,第二个是string类型的对象,getline函数的功能是读取文件中换行符前的一行字符串,与输入操作符<<不同的是,getline函数不避空白字符(即空格键),即不被空白字符终止,且行前的空白字符或者制表符也照读。getline函数不读入换行符。<<输入操作符读取字符串时,遇到空白字符的中断。

string::size()函数可以读取string字符串中字符的个数,包括空白字符和换行符。

例子程序:

int main()
{
    ifstream inf;
    inf.open("test.txt");
    string line;
    inti=0;
    while(getline(inf,line))
    {
        cout<<""<<i<<"行有"<<line.size()<<"个字符"<<endl;
        cout<<line<<endl;
    }
    inf.close();
    string str="\tHelloWorld!\n";
    cout<<"字符串"<<str<<"的长度为"<<str.size()<<endl;
    system("PAUSE");
    return 0;
}

运行结果:

第0行有12个字符

Hello World!

字符串 Hello World!

的长度为14

请按任意键继续. . .

注解:在string::size()函数中,\t和\n分别算作一个字符。空格也算作一个字符。在读取文件的例子中,虽然文件的行尾有换行符\n,但是因为getline函数并不读入换行符,所以显示line对象中字符的个数为12个。

posted @ 2014-05-07 16:24  星辰风  阅读(204)  评论(0编辑  收藏  举报