2011-01-28 25 views
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; 
} 

這只是一個小試驗程序來測試這個循環。我正在處理的程序是關於從用戶確定的序列中取出元音和打印元音的。直到用戶輸入字符串纔會定義字符串。感謝您提前幫助您的人。字符串下標超出範圍。字符串大小是未知的和循環字符串,直到空

回答

4

嘗試此您的循環:

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

問題是該字符串不是像C字符串那樣的空終止字符數組。嘗試在超出字符串長度的位置調用[]運算符會導致報告的錯誤。對於以空字符結尾的字符數組,使用string :: c_str()方法 – Keith 2011-01-28 04:23:13

4

std::string的大小未知的 - 你可以使用std::string::size()成員函數得到它。另請注意,與C字符串不同,std::string類不必以null結尾,所以不能依賴空字符來終止循環。

事實上,使用std::string更好,因爲您總是知道尺寸。像所有C++容器一樣,std::string也帶有內置迭代器,它允許您安全地遍歷字符串中的每個字符。成員函數std::string::begin()爲您提供了一個指向字符串開頭的迭代器,而std::string::end()函數爲您提供了一個指向最後一個字符之後的迭代器。

我推薦使用C++迭代器。使用迭代器處理字符串的典型循環可能如下所示:

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 
}