为什么此代码会出错:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
char x='\0',i=0;
vector<char> text;
do
{
cout<< "Enter a char" << endl;
cin>>x;
if(x<65||(x>90&&x<97)||x>123)
{
cout<<"Out of Range-Please Enter Letters"<<endl;
continue;
}
text.push_back(x);
if(x=='n'||x=='N'){
text.clear();
cout<<"Vector Cleared"<<endl;
continue;
}
cout<<text.size()<<endl;
cout<<"Vector now holds\n";
for(i=0;i< signed (text.size() ) ;i++)
{
cout<< text[i] << endl;
}
}while(x!='y');
cout << "Vector size is " << text.size() << " Vector Capacity is " << text.capacity() << endl;
vector<char>::iterator it = text.begin();
for (; it != text.end() ; it++)
cout << *it << endl;
cout << "Enter Position to delete: " << endl;
cin >> i;
text.erase(text.begin() + i - 1);
it = text.begin() ;
for (; it != text.end() ; it++)
cout << *it << endl;
}
调试断言失败,表达式向量迭代器+偏移超出范围。
答案 0 :(得分:2)
它会崩溃,因为i
是一个字符,因此cin
会读取一个字符。例如,如果有人输入值8
,则i
的值将为38(如果您的平台使用ASCII编码)。
测试字符值是非常糟糕的做法,而不是使用isalpha()
标题中的cctype
。
答案 1 :(得分:0)
您的部分问题是您使用char
作为数组索引:
cout<< text[i] << endl;
您还应该考虑非基本类型的前缀(而不是后缀)运算符,以提高您在这些方面的表现:
for (; it != text.end() ; it++)
和
for (; it != text.end() ; it++)
答案 2 :(得分:0)
建议:
std::string
代替
std::vector<char>
。isprint, isdigit, isalpha,
等。)tolower
或toupper
。我将您的示例转换为使用std::string
,字符函数和运算符周围的空间。与您的风格相比,简单易读:
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char x='\0';
unsigned int i=0;
string text;
do
{
cout<< "Enter a char" << endl;
cin>>x;
// if(x<65||(x>90&&x<97)||x>123)
if (! isprint(x))
{
cout<<"Out of Range-Please Enter Letters"<<endl;
continue;
}
text += x;
if(toupper(x) == 'N')
{
text.clear();
cout<<"String Cleared"<<endl;
continue;
}
cout << text.length() << endl;
cout<<"String now holds\n";
cout << text << endl;
}while(tolower(x) != 'y');
cout << "String length is: " << text.length() << ", capacity: " << text.capacity() << endl;
cout << text << endl;
cout << "Enter Position to delete: " << endl;
cin >> i;
text.erase(text.begin() + i - 1);
cout << "After erase: " << text << endl;
return 0;
}