开发者

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

#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 vowel开发者_运维问答s 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.


Try this for your loop:

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


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜