字符串下标超出范围。字符串大小未知并循环字符串直到 null
#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;
}
这只是一个测试这个循环的小试验程序。我正在开发的程序是关于元音并根据用户确定的序列打印元音的。在用户输入之前,该字符串不会被定义。提前感谢你们的帮助。
#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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在你的循环中尝试这个:
Try this for your loop:
std::string
的大小并非未知 - 您可以使用std::string::size()
成员函数获取它。另请注意,与 C 字符串不同,std::string
类不必以 null 终止,因此您不能依赖 null 字符来终止循环。事实上,使用
std::string
更好,因为您始终知道大小。与所有 C++ 容器一样,std::string 也带有内置迭代器,它允许您安全地循环字符串中的每个字符。std::string::begin()
成员函数为您提供一个指向字符串开头的迭代器,而std::string::end()
函数为您提供一个指向最后一个字符之后的迭代器。我建议熟悉 C++ 迭代器。使用迭代器处理字符串的典型循环可能如下所示:
The size of an
std::string
is not unknown - you can get it using thestd::string::size()
member function. Also note that unlike C-strings, thestd::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. Thestd::string::begin()
member function gives you an iterator pointing to the beginning of the string, and thestd::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: