这里的istream& getline (istream& is, string& str);字符串在换行符之后终止。但是如果我想处理str包含2-3行的情况,那么替代方案是什么呢?
发布于 2013-08-23 13:58:05
您可以给出一条消息,告诉用户终止输入。
std::cout<<"Enter your message (enter finish. to terminate input)"<<endl;
while (mess != "finish.")
{
std::getline(std::cin, mess);
input_message += mess;
}我希望这会有所帮助,因为它更具动态性
发布于 2013-08-23 13:55:18
我觉得我们可以使用一些示例输入,但此代码将从std::cin读取行,直到找不到更多的行,并将所有这些行保存到std::vector中。
#include <iostream>
#include <vector>
int main() {
std::string line;
std::vector<std::string> lines;
while (std::getline(std::cin, line)) { // iterates until exhaustion
lines.push_back(line);
}
// lines[k] can be used to fetch the k'th line read, starting from index 0
// Simply repeat the lines back, prepended with a "-->"
for (auto line : lines) {
std::cout << "--> " << line << '\n';
}
}例如,如果我输入
cat
bat
dog我的程序输出
--> cat
--> bat
--> doghttps://stackoverflow.com/questions/18395521
复制相似问题