C++ 字符串下标超出范围。字符串大小未知,正在循环字符串直至为null #包括 #包括 #包括 #包括 使用名称空间std; int main() { 字符串字; int j=0; cin>>单词; while(单词[j]){ cout

C++ 字符串下标超出范围。字符串大小未知,正在循环字符串直至为null #包括 #包括 #包括 #包括 使用名称空间std; int main() { 字符串字; int j=0; cin>>单词; while(单词[j]){ cout,c++,string,loops,null,undefined,C++,String,Loops,Null,Undefined,为您的循环尝试以下方法: #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 <&

为您的循环尝试以下方法:

#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;
}
while(jcoutstd::string
的大小不是未知的-您可以使用
std::string::size()
成员函数获得它。还要注意的是,与C-strings不同,
std::string
类不必以null结尾,因此您不能依赖null字符来终止循环

实际上,使用<代码> STD::String STD::Stry还有内置的迭代器,它允许您安全地循环字符串中的每个字符。<代码> STD::String::开始()member函数提供指向字符串开头的迭代器,而

std::string::end()
函数提供指向最后一个字符的迭代器

<>我建议对C++迭代器变得舒服。使用迭代器处理字符串的典型循环可能看起来像:

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

问题是字符串不像C字符串那样是以null结尾的字符数组。尝试在字符串长度之外调用[]运算符会导致报告的错误。对于以null结尾的字符数组,请使用string::C_str()方法+1 word.length()我个人更喜欢这种情况下的循环。
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
}