【发布时间】:2014-04-03 00:22:38
【问题描述】:
我想知道如何知道循环中 std::string 的结尾?
例如:
while(string.eof()) {}
记住它与 std::string 一起使用
谢谢大家。
【问题讨论】:
-
使用
str.begin()和str.end()。 -
请注意,
while (!eof())通常使用非常错误。
我想知道如何知道循环中 std::string 的结尾?
例如:
while(string.eof()) {}
记住它与 std::string 一起使用
谢谢大家。
【问题讨论】:
str.begin()和str.end()。
while (!eof()) 通常使用非常错误。
您可以像循环标准库容器一样循环字符串:
for (auto c : s)
{
// do something with c
}
或
for (auto it = s.begin(), end = s.end(); it != end; ++it)
{
// do something with it
}
s 是字符串。
【讨论】:
c 或it。
你可以使用迭代器
string str="abcd";
string::iterator it=str.rbegin();//iterator pointing on d
如果你想在最后一个字符之前做一些事情,你可以这样做
for (string::iterator it2=str.begin(); it"!=str.rbegin();++it){
cout<<"Inside the string but not the last character\n";
}
【讨论】:
"我不想和字符串交互,只想要一个循环,而 字符串的结尾没有出现。”
实际上,字符串是一个容器(特定数组),而不是文件。它不支持任何state,也没有像eof 这样的方法。所以你不能这样做。
如果您有通常的数组char buf[SZ];,那么“数组的末尾没有到来”是什么?
毫无意义。数组索引可以指向最后一个元素,上面显示的字符串迭代器也是如此。
【讨论】: