2011-01-28 23 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 
}