用C++清理一串标点符号

Bra*_*gen 8 c++

好吧,在我提出问题之前我想说清楚一件事.我目前是NIU计算机科学专业的学生,​​这与我在那里的课程作业有关.因此,如果有人有问题,请不要再阅读,继续关注您的业务.

现在对于任何愿意帮助这一情况的人来说.对于我目前的作业,我们必须阅读一个只是一个文本块的文件.对于文件中的每个单词,我们要清除单词中的任何标点符号(例如:"不能"将最终为"can","that - to"将最终显示为"that",显然没有引号,引号仅用于指定示例的内容).

我遇到的问题是我可以清理字符串,然后将其插入我们正在使用的地图中但由于某些原因,我编写的代码允许将空字符串插入到地图中.现在我已经尝试了所有可以阻止这种情况发生的事情,我唯一想到的就是在地图结构中使用擦除方法.

所以我正在寻找的是两件事,任何关于我如何能够解决这个问题的建议只是简单地删除它而b)我可以对我已编写的代码进行任何改进.

以下是我从文件中读取的函数,然后是清理它的函数.

注意:从文件读入的函数调用clean_entry函数以在将任何内容插入到映射之前去掉标点符号.

编辑:谢谢克里斯.数字是允许的:).如果有人对我写的代码有任何改进,或者对我所做的事情有任何批评,我会听.在学校,我们真的不能以正确,适当或最有效的方式反馈.

int get_words(map<string, int>& mapz)
{
 int cnt = 0;               //set out counter to zero

 map<string, int>::const_iterator mapzIter;

 ifstream input;            //declare instream
 input.open( "prog2.d" ); //open instream
 assert( input );           //assure it is open

 string s;                  //temp strings to read into
 string not_s;

 input >> s;

 while(!input.eof())        //read in until EOF
  {
   not_s = "";
   clean_entry(s, not_s);

   if((int)not_s.length() == 0)
    {
     input >> s;
     clean_entry(s, not_s);
    }    

   mapz[not_s]++;              //increment occurence
   input >>s;
  }
 input.close();     //close instream 

 for(mapzIter = mapz.begin(); mapzIter != mapz.end(); mapzIter++)
  cnt = cnt + mapzIter->second;

 return cnt;        //return number of words in instream
}


void clean_entry(const string& non_clean, string& clean)
{
 int i, j, begin, end;

 for(i = 0; isalnum(non_clean[i]) == 0 && non_clean[i] != '\0'; i++);

 begin = i;

 if(begin ==(int)non_clean.length())
   return;

 for(j = begin; isalnum(non_clean[j]) != 0 && non_clean[j] != '\0'; j++);

 end = j;

 clean = non_clean.substr(begin, (end-begin));

 for(i = 0; i < (int)clean.size(); i++)
  clean[i] = tolower(clean[i]);

}
Run Code Online (Sandbox Code Playgroud)

Chr*_*org 7

空条目的问题在于while循环.如果你得到一个空字符串,你清理下一个字符串,并添加它而不检查.尝试改变:

not_s = "";
clean_entry(s, not_s);

if((int)not_s.length() == 0)
 {
  input >> s;
  clean_entry(s, not_s);
 }    

mapz[not_s]++;              //increment occurence
input >>s;
Run Code Online (Sandbox Code Playgroud)

not_s = "";
clean_entry(s, not_s);

if((int)not_s.length() > 0)
{
    mapz[not_s]++;              //increment occurence
}    

input >>s;
Run Code Online (Sandbox Code Playgroud)

编辑:我注意到你正在检查字符是否是字母数字.如果不允许使用数字,您可能还需要重新访问该区域.