【问题标题】:String subscript out of range. String size is unknown and looping string until null字符串下标超出范围。字符串大小未知并且循环字符串直到为空
【发布时间】:2011-01-28 04:05:44
【问题描述】:
#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;
}

这只是一个小试验程序来测试这个循环。我正在处理的程序是关于元音和从用户确定的序列中打印元音。在用户输入之前,该字符串才被定义。谢谢你们提前帮助。

【问题讨论】:

    标签: c++ string loops null undefined


    【解决方案1】:

    在你的循环中试试这个:

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

    【讨论】:

    • 问题在于该字符串不是像 C 字符串那样以空字符结尾的字符数组。尝试调用超出字符串长度的 [] 运算符会报告错误。对于以空字符结尾的字符数组,使用 string::c_str() 方法
    • +1 word.length() 也可以工作,我个人更喜欢 for 循环来处理这种情况。
    【解决方案2】:

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

    事实上,使用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
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-06
      • 2015-03-31
      • 1970-01-01
      • 2013-04-22
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多