string 中 getline && erase

getline的用法:


(1)
istream& getline (istream& is, string& str, char delim);
(2)
istream& getline (istream& is, string& str);

Get line from stream into string
Extracts characters from  is and stores them into  str until the delimitation character  delim is found (or the newline character,  '\n', for  (2)).

The extraction also stops if the end of file is reached in  is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.

Each extracted character is appended to the  string as if its member  push_back was called.

	string str,str1;
	char delim = 'r';
	
	getline(cin,str,delim);
	getline(cin,str1); //getline()的两种用法.'r'是结束符.没有默认是'\n'.遇到结束符后读取并将其丢弃
	
	cout<<"str="<<str<<endl;
	cout<<"str1="<<str1<<endl;//这里没有'r'

输入:hello world

输出:

str=hello wo
str1=ld



erase的用法

sequence (1)
 string& erase (size_t pos = 0, size_t len = npos);
character (2)
iterator erase (iterator p);
range (3)
     iterator erase (iterator first, iterator last);

Erase characters from string
Erases part of the  string, reducing its  length:

(1) sequence
Erases the portion of the string value that begins at the character position  pos and spans  len characters (or until the  end of the string, if either the content is too short or if  len is  string::npos.
Notice that the default argument erases all characters in the string (like member function  clear).
(2) character
Erases the character pointed by  p.
(3) range
Erases the sequence of characters in the range  [first,last).

Return value

The  sequence version (1) returns  *this.
The others return an iterator referring to the character that now occupies the position of the first character erased, or  string::end if no such character exists.

Member type  iterator is a  random access iterator type that points to characters of the  string.

// string::erase
#include <iostream>
#include <string>

int main ()
{
  std::string str ("This is an example sentence.");
  std::cout << str << '\n';
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '\n';
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '\n';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '\n';
                                           // "This sentence."
  return 0;
}

输出:

This is an example sentence.
This is an sentence.
This is a sentence.
This sentence.








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值