user3029001
user3029001

Reputation: 439

C++ string and arrays

If string is just an array of chars, then is it considered bad coding to directly access an index of a string? for example...

 string test = "Hello"; 
 cout << text.[0];

 int lenOfTest = (int)test.length();
 for(int i = 0; i < lenOfTest; i++ ){
   cout << test[i];
 }

Upvotes: 0

Views: 76

Answers (2)

lucasmoura
lucasmoura

Reputation: 275

I don't think it is a bad practice to access a char element using the operator[], however keep in mind that accessing a character like this will not raise an exception in case a invalide position is being used. To raise an exception, use the string::at.

Upvotes: 2

Massa
Massa

Reputation: 8972

A std::string is not a simple array of char, although it is a container of char, and yes, you can access each of its elements normally. Just don't use the point before the open [ like you did in your second line.

Upvotes: 3

Related Questions