分类: C/C++
2015-07-08 22:05:31
第三章
引入两种基本标准库类型 string 和 vector ;
Using 声明 :使程序更简洁
字符串类型与字符串字面值 不是一种类型
空格 ‘\040’
Getline(cin, s1) 按行输出
3.6答案:string类型的标准输入操作符对空白字符的处理:读取并忽略有效字符(非空白字符)之前所有的空白字符,然后读取字符直至再次遇到空白字符,读取终止(该空白字符仍然留在输入流中)。
getline函数对空白字符的处理:不忽略行开头的空白字符,读取字符直至遇到换行符,读取终止并丢弃换行符(换行符从输入流中去掉但并不存储在string对象中)。 不是很理解?
3.10课后题中,程序为:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s1;
cin>>s1;
for(string::size_type index=0;index!=s1.size();++index)
{
if(ispunct(s1[index]))
;
else cout<<s1[index];
}
cout<<endl;
}
结果:
tanjianghui@ubuntu:~/tanjianghui$ ./huihui5
hello,,my,girl ,hi. “girl后面有空格”
hellomygirl
tanjianghui@ubuntu:~/tanjianghui$ ./huihui5
helle ,my “helle后面有空格” why 遇到空格就结束
helle
tanjianghui@ubuntu:~/tanjianghui$ ./huihui5
hello,my,girl,hi
hellomygirlhi
tanjianghui@ubuntu:~/tanjianghui$
如果修改一行程序: 即使用getline 函数 而不是用cin
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s1;
getline(cin,s1);
for(string::size_type index=0;index!=s1.size();++index)
{
if(ispunct(s1[index]))
;
else cout<<s1[index];
}
cout<<endl;
}
结果: 空格可以输出,且遇空格不会结束
tanjianghui@ubuntu:~/tanjianghui$ ./huihui5
hello ,my
hello my “hello后面空格输出”
tanjianghui@ubuntu:~/tanjianghui$
总之一句话:cin遇到空格就退出,即空格是string结束的标志;但是getline函数不会。
3.14
#include<string>
#include<iostream>
#include<vector>
#include<cctype>
using namespace std;
int main()
{
vector<string> s1;
int k=0;
string s2;
getline(cin,s2);
s1.push_back(s2);
for(vector<string>::size_type idx=0;idx!=s1.size();++idx)
{
for(string::size_type index=0;index!=s1[idx].size();++index)
{ s1[idx][index]=toupper(s1[idx][index]);
k++;
}
cout<<s1[idx];
if(k%8==0)
cout<<endl;
}
cout<<endl;
return 0;
}
一直无法实现每八个单词换行的功能? 暂时放弃
Const vector<>::iterator 与 vector<>::const_iterator的区别 p86
Const vector<>::iterator : 迭代器本身的值不能改变,即不能进行自增运算;
vector<>::const_iterator : 迭代器不能进行解引用运算,即不能赋值;
采用下列程序会出现什么结果
vector<int> vi;
Vector<int>::iterator mid=(vi.begin()+vi.end())/2 ; // 编译错误,因为没有两个迭代器想加的操作是未定义的,
迭代器的算术操作定义:迭代器+n
迭代器1-迭代器2