samedi 19 avril 2014

Chaîne C++ et tableaux - Stack Overflow


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];
}



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.




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.



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];
}


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.



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.


0 commentaires:

Enregistrer un commentaire