[英]Identifying C 11 keywords in Strings (string.at() issues)
我已经成功地在教授提供的主要功能的代码片段中搜索了c ++ 11关键字。 尽管当打印的关键字包含在其他单词中时,将在打印这些关键字时进行打印,例如,当字符串片段中存在甜甜圈时,将打印do。 因此,我创建了两个if语句,这些语句标识字符串中的下一个char以及是否为空格字符,如果是则继续打印它。 但是我在x.at()语句中遇到了一个问题,该问题可以编译但无法运行。 有人知道我在做什么错吗?
// C++11 Keyword Search Program
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
typedef vector<string> string_vector;
// return the C++11 keywords that appear in the code snippet
string_vector find_keywords(const string snippet)
{
const string x=snippet;
int len=x.length();
int back=x.back();
int last_char, first_char;
vector<string> answer;
string keywords[]= {"alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand",
"bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "const", "constexpr",
"const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum",
"explicit", "export", "extern", "false", "float", "for","friend", "goto", "if", "inline", "int", "long", "mutable",
"namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected public",
"register", "reinterpret_cast","return","short","signed","sizeof","static","static_assert","static_cast","struct",
"switch", "template", "this","thread_local","throw","true","try","typedef","typeid","typename","union","unsigned",
"using","virtual","void", "volatile","wchar_t","while","xor","xor_eq"};
for(int i=0;i<83;++i)
{
string test=keywords[i];
size_t found = x.find(test);
unsigned int testsize=test.size();
int test1=0,test2=0;
if(found!=string::npos)
{
char a=x.at(found-1);
char b=x.at(found+testsize);
int c=isalpha(a);
int d=isalpha(b);
if (c>=1)
test1=1;
if (d>=1)
test2=1;
}
if(found!=string::npos && test1==0 &&test2==0)
cout<<test<<" ";
}
return answer;
}
int main (int argc, char* const argv[])
{
const string snips[] =
{
"int i = 0;",
"i += 1;",
"return (double) x / y;",
"char foo(char bar);",
"double bar(void) const",
"garbage = fuzz + lint;"
};
const string_vector snippets(snips,snips + 6);
for (auto snippet : snippets)
{
cout << "**Snippet** " << snippet << endl << "**Keywords** ";
for (auto keyword : find_keywords(snippet))
{
cout << ' ' << keyword;
}
cout << endl << endl;
}
return EXIT_SUCCESS;
}
last_char=found+len-1; char2=x.at(last_char);
一旦found > 0
,则last_char >= x.length()
并且您的at()
调用尝试越界读取。
还要注意,空格不是唯一可能的令牌定界符。 一个人通常会写诸如break;
东西break;
,或return;
, while(condition)
或f(int[])
或this->member
。 所有这些都包含一个不被空格包围的关键字。
并且,看起来像关键字的字符串可能会出现在字符串文字中"like this"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.