getline是从流中获取一行信息输入到字符串中:
(1) | istream& getline (istream& is, string& str, char delim); istream& getline (istream&& is, string& str, char delim); |
---|---|
(2) | istream& getline (istream& is, string& str); istream& getline (istream&& is, string& str); |
从is中提取字符并将其存储到str中,直到找到定界字符delim(或换行字符“n”,对于(2))。
如果在is中到达文件结束,或者在输入操作期间发生其他错误,则提取也将停止。如果找到分隔符,则提取并丢弃分隔符(即不存储分隔符,然后将开始下一个输入操作)。注意,在调用之前,str中的任何内容都将被新提取的序列替换。每个提取的字符都被追加到字符串中,就像调用了它的成员push_back一样。
example1:
// extract to string
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
example2:
class Solution {
public:
string simplifyPath(string path) {
string res, t;
stringstream ss(path);
vector<string> v;
//提取字符,遇到/则停止
while (getline(ss, t, '/')) {
if (t == "" || t == ".") continue;
if (t == ".." && !v.empty()) v.pop_back();
else if (t != "..") v.push_back(t);
}
for (string s : v) res += "/" + s;
return res.empty() ? "/" : res;
}
};