C++ 为什么这个代码总是崩溃
此代码产生错误的原因:C++ 为什么这个代码总是崩溃,c++,arrays,vector,C++,Arrays,Vector,此代码产生错误的原因: #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|
#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;
}
#包括
#包括
使用名称空间std;
int main()
{
字符x='\0',i=0;
矢量文本;
做
{
coutx;
如果(x90和x123)
{
cout它将崩溃,因为i
是一个字符,因此cin
将读取一个字符。例如,如果有人输入值8
,则i
的值将为38(如果您的平台使用ASCII编码)
另外,测试字符的值是非常糟糕的做法,请使用cctype
标题中的isalpha()
。部分问题是您使用char
作为数组索引:
cout建议:
使用std::string
代替
std::vector
使用字符常量而不是
他们的ASCII十进制数('A'
而不是65岁)
更喜欢库函数而不是
比较字符范围(请参见
isprint、isdigit、isalpha等)
将文本和字符转换为大写
比较前使用小写或小写
tolower
或touper
首选每个变量声明一个变量
线路
在运算符周围添加空格,
提高可读性
我将您的示例转换为使用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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符x='\0';
无符号整数i=0;
字符串文本;
做
{
coutx;
//如果(x90和x123)
如果(!isprint(x))
{
输入是什么?您是否设置了断点并逐步完成了程序?text.erase(text.begin()+i-1);如果i>text.size()或i<1,则应失败,这可能是问题所在?程序在哪一行崩溃?我可以看到它与文本一起发生。erase如果为i输入0,则尝试擦除text.begin()之前的位置。