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.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
Brion
  • 1
  • 1
  • 1

2 Answers2

4

Try this for your loop:

while(j < word.size()){
  cout << "idk";
  j++;
}
chrisaycock
  • 36,470
  • 14
  • 88
  • 125
  • 3
    The issue being that string is not a null terminated character array like a C-String. Attempting to call the [] operator beyond the length of the string gives the reported error. For a null terminated character array, use the string::c_str() method – Keith Jan 28 '11 at 04:23
  • +1 word.length() would also work, and personally I prefer for loops for situations like this one to a while. – nybbler Jan 28 '11 at 04:27
4

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
}
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140