知道循环中 std::string 的结尾

Knowing the end of a std::string in a loop

本文关键字:string 结尾 std 循环      更新时间:2023-10-16

我想知道如何知道循环中 std::string 的结尾?

例如:

while(string.eof()) {}

记住它是用 std::string

谢谢大家。

您可以像循环访问标准库容器一样遍历字符串:

for (auto c : s)
{
  // do something with c
}

for (auto it = s.begin(), end = s.end(); it != end; ++it)
{
  // do something with it
}

其中s是字符串。

您可以使用迭代器

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 charactern";
}

"我不想与字符串交互,只是想要一个循环,而 弦的尽头没有来。

实际上,字符串是一个容器(特定数组),而不是文件。它不支持任何状态,也没有任何方法,如 eof .所以你不能这样做。

如果您有常用的数组char buf[SZ];那么"数组的末尾不会到来"是什么?毫无 意义。数组索引可以指向最后一个元素,上面显示的字符串迭代器也是如此。