String subscript out of range. String size is unknown and looping string until null

♀尐吖头ヾ 提交于 2020-01-07 04:38:34

问题


#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.


回答1:


Try this for your loop:

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



回答2:


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
}


来源:https://stackoverflow.com/questions/4824735/string-subscript-out-of-range-string-size-is-unknown-and-looping-string-until-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!