【问题标题】:how to Restrict char array to take only a's and b's from string in c++?c++ - 如何限制char数组仅从c ++中的字符串中获取a和b?
【发布时间】:2018-05-16 01:19:58
【问题描述】:

我有一个程序,它接受字符串并将其转换为 char 数组。我想创建没有正则表达式库的正则表达式,该库接受所有在某处具有aa 的a 和b 字符串。

我下面的代码工作正常,但唯一的问题是它也接受除 a 和 b 以外的字符,例如它也接受 baabss。 您能否帮助更正代码以使其在这种情况下拒绝该字符串?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string input_string;
    char char_string[20];
    int counter=0;

    cout << "type in some input text:$" << endl;
    cin >> input_string;

    strcpy(char_string, input_string.c_str());

    for (int i = 0;  i < sizeof(input_string); i++)
    {
        if(char_string[i]=='a' || char_string[i]=='b'){
            switch(char_string[i])
            {
             case 'a' :
                 counter++;
                 break;              
             case 'b' :
                 if(counter==1){
                     counter=0;
                 }               
                 break;
            }
         }
     }

     if(counter==2){
        cout << "String accepted" << endl;
     }
     else{
        cout << "String not accepted" << endl;
     }
     std::cin.get();
     system ("PAUSE");   
}

【问题讨论】:

  • 为什么需要转换成字符数组? operator[] 将与 std::string 一起使用。
  • 我这样做是为了将每个字符与 switch 语句匹配
  • @Inam 问题是如果字符串有外来字符,您不会拒绝该字符串
  • @JakeFreeman...谢谢先生,我现在明白了,我跳过了其他部分,现在它可以工作了
  • @Inam 你能支持我的评论吗?

标签: c++ arrays string


【解决方案1】:

无效字符问题

在你的循环体中,你必须拒绝既不是 a 也不是 b 的字符。所以你必须完成

   if(char_string[i]=='a' || char_string[i]=='b'){
       ...
   }

带有else 子句。例如:

   else {
       counter=0;   // reset the counter so that the final check will fail
       break;       // exit the for loop
   } 

目前尚未发现的问题

第一个问题是sizeof(input_string) 没有返回您所期望的!请改用input_string.size()

然后程序将无法接受baaab,因为它会导致循环以计数器为3结束。因此您必须将最终检查更改为:

 if(counter>=2){  // instead of ==

糟糕!

最后,如果您的用户输入超过 19 个字符,您的程序将出现未定义的行为,因为 strcpy() 会复制比数组中的位置更多的字符,从而导致内存损坏。您可以用来纠正此问题的策略:

  1. 使用&lt;iomanip&gt;限制接受的用户输入的大小(例如cin &gt;&gt; setw(19) &gt;&gt;input_string;

  2. 使用strncat() 限制副本的大小,并在输入被截断时通知用户。然后,您还必须确保循环不会超出截断的大小。

  3. 您可以直接访问input_string 中的原始字符,而无需进行任何复制。或者,如果您愿意,可以将 char 数组替换为将从字符串初始化的向量:vector&lt;char&gt;char_string(input_string.begin(), input_string.end());

Online demo of option 3

【讨论】:

  • christphe...谢谢先生,我明白了,现在工作正常...你很棒
猜你喜欢
  • 1970-01-01
  • 2015-06-19
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
相关资源
最近更新 更多