C++String的注意点和getline

1.String中的size()使用
通常我们在刷算法题的时候,进行string的进行搜索时,会使用到size()这个类型例如:
for(int i=0;i<str1.size();i++)
{
//内容题
}
此时发现,str.size()的返回值类型为Unsigned char;
所以如果使用int 进行比较的话,如果int为负,则会出现逻辑误差。
例如:
int main()
{
/string word;
while (cin >> word)
{
cout << word << endl;
}
/
string line;
while (getline(cin, line))
{
cout << line << endl;
}
bool ret = false;
if (line.size() < -1)
{
ret = true;
}
cout << ret << endl;
system(“pause”);
return 0;
}
此时的ret返回值为true,与初衷不符合。
因此C++圣经说不建议使用int 和size混用。

要使用的话就用unsigned char;

2.使用getline
所有的函数格式,都需要看他的形参列表,getline(cin,str,delm)
delm为分隔符,如果不适用的话默认为回车
根据操作系统的不懂,Windows下退出循环为Ctrl+z
下面几个示例:
1.如果使用str在外面定义,当退出while时,str还是为空,被擦除。
string line;
string resultline;
while (getline(cin, line))
{
//resultline = line;
cout << line << endl;
}

bool ret = false;
for (auto &c : line)
{
	c = toupper(c);
}
cout << line << endl;
system("pause");
return 0;
}

line为空。

2.如果使用,为分隔符
int main()
{
/string word;
while (cin >> word)
{
cout << word << endl;
}
/
string line;
string resultline;
while (getline(cin, line,’,’))
{
//resultline = line;
cout << line << endl;
}

bool ret = false;
for (auto &c : line)
{
	c = toupper(c);
}
cout << line << endl;
system("pause");
return 0;

}
输入hello,world
后显示hello
!!!注意此处,再次输出ni,hao
line的值为world,ni,因为endl会将缓冲区刷出。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值