字符串下标超出范围.字符串大小未知,并且循环字符串直到为空 [英] String subscript out of range. String size is unknown and looping string until 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;
}
这只是一个小试验程序,用于测试此循环.我正在研究的程序是有关元音和按照用户确定的顺序打印元音的.直到用户键入该字符串才定义.谢谢您的帮助.
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.
推荐答案
std::string
的大小不是 未知-您可以使用std::string::size()
成员函数来获取它.还要注意,与C字符串不同,std::string
类不必以空值结尾,因此您不能依赖空值字符来终止循环.
The size of an std::string
is not unknown - you can get it using the std::string::size()
member function. Also note that unlike C-strings, the std::string
class does not have to be null-terminated, so you can't rely on a null-character to terminate a loop.
实际上,与std::string
一起使用会更好,因为您始终知道大小.与所有C ++容器一样,std::string
也带有内置的迭代器,可让您安全地循环遍历字符串中的每个字符. std::string::begin()
成员函数为您提供一个指向字符串开头的迭代器,而std::string::end()
函数为您提供一个指向最后一个字符之后的迭代器.
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. The std::string::begin()
member function gives you an iterator pointing to the beginning of the string, and the std::string::end()
function gives you an iterator pointing to one past the last character.
我建议您熟悉C ++迭代器.使用迭代器处理字符串的典型循环如下所示:
I'd recommend becoming comfortable with C++ iterators. A typical loop using iterators to process the string might look like:
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
}
这篇关于字符串下标超出范围.字符串大小未知,并且循环字符串直到为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!