字符串下标超出范围。字符串大小未知并循环字符串直到 null

发布于 2024-10-15 02:57:26 字数 391 浏览 7 评论 0原文

#include<iostream>
#include<cmath>
#include<iomanip>
#include<string>

using namespace std;

int main()
{
 string word;
 int j = 0;

 cin >> word;

 while(word[j]){
 cout << "idk";
 j++;
 }
 cout << "nope";



 system("pause");
 return 0;
}

这只是一个测试这个循环的小试验程序。我正在开发的程序是关于元音并根据用户确定的序列打印元音的。在用户输入之前,该字符串不会被定义。提前感谢你们的帮助。

#include<iostream>
#include<cmath>
#include<iomanip>
#include<string>

using namespace std;

int main()
{
 string word;
 int j = 0;

 cin >> word;

 while(word[j]){
 cout << "idk";
 j++;
 }
 cout << "nope";



 system("pause");
 return 0;
}

This is just a little trial program to test this loop out. The program I am working on is about vowels and printing vowels out from a sequence determined by the user. The string isn't defined until the user types in. Thank you for your guys help in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋心╮凉 2024-10-22 02:57:26

在你的循环中尝试这个:

while(j < word.size()){
  cout << "idk";
  j++;
}

Try this for your loop:

while(j < word.size()){
  cout << "idk";
  j++;
}
手心的温暖 2024-10-22 02:57:26

std::string 的大小并非未知 - 您可以使用 std::string::size() 成员函数获取它。另请注意,与 C 字符串不同,std::string 类不必以 null 终止,因此您不能依赖 null 字符来终止循环。

事实上,使用 std::string 更好,因为您始终知道大小。与所有 C++ 容器一样,std::string 也带有内置迭代器,它允许您安全地循环字符串中的每个字符。 std::string::begin() 成员函数为您提供一个指向字符串开头的迭代器,而 std::string::end() 函数为您提供一个指向最后一个字符之后的迭代器。

我建议熟悉 C++ 迭代器。使用迭代器处理字符串的典型循环可能如下所示:

for (std::string::iterator it = word.begin(); it != word.end(); ++it)
{
   // Do something with the current character by dereferencing the iterator
   // 
   *it = std::toupper(*it); // change each character to uppercase, for example
}

The size of an std::string is not unknown - you can get it using the std::string::size() member function. Also note that unlike C-strings, the std::string class does not have to be null-terminated, so you can't rely on a null-character to terminate a loop.

In fact, it's much nicer to work with std::string because you always know the size. Like all C++ containers, std::string also comes with built-in iterators, which allow you to safely loop over each character in the string. The std::string::begin() member function gives you an iterator pointing to the beginning of the string, and the std::string::end() function gives you an iterator pointing to one past the last character.

I'd recommend becoming comfortable with C++ iterators. A typical loop using iterators to process the string might look like:

for (std::string::iterator it = word.begin(); it != word.end(); ++it)
{
   // Do something with the current character by dereferencing the iterator
   // 
   *it = std::toupper(*it); // change each character to uppercase, for example
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文