【问题标题】:How can I read a string without punctuation by scanf()?如何通过 scanf() 读取没有标点符号的字符串?
【发布时间】:2020-01-25 09:01:44
【问题描述】:

我编写了这段代码,但它没有避免使用标点符号。

   string str;
   char ch[100];
   while(scanf("%s[a-z | A-Z ]",ch)!=EOF) 
   {
        str=ch;
        cout<<str<<endl;
   }

当我给出以下输入时:

 road.sign read:
 went home.

它打印以下输出:

road.
sign
read:
went
home.

有没有什么办法可以改进这个代码以打印不带标点的单词?

【问题讨论】:

  • c++ 中有cin/getline 时,为什么还要使用scanf
  • cin 有什么方法可以避免输入时出现标点符号吗? getline 将存储一整行,但我需要一个单词来存储。
  • The Regex in scanf goes between % and s like %[^\n]s

标签: c++ string input scanf


【解决方案1】:

解决方案可以存储整个句子,然后使用正则表达式替换删除标点符号。

#include <iostream>
#include <regex>

using namespace std;

int main() {

    std::string str;
    std::regex reg(R"([.,\/#!$%\^&\*;:{}=\-_`~()])");

    while(scanf("%s", str)!=EOF)
    {

        // Remove punctation
        str = regex_replace(str, reg, "");

        std::cout<<str<<std::endl;

    }

}

【讨论】:

    【解决方案2】:

    我从GeeksforGeeks Tutorial 获得了一个示例,用于从 C++ 中的char 字符串中删除一个字符:

    #include <bits/stdc++.h> 
    using namespace std; 
    
    void removeChar(char *s, int c){ 
    
        int j, n = strlen(s); 
        for (int i=j=0; i<n; i++) 
           if (s[i] != c) 
              s[j++] = s[i]; 
    
        s[j] = '\0'; 
    } 
    
    int main() 
    { 
       char s[] = "geeksforgeeks"; 
       removeChar(s, 'g'); 
       cout << s; 
       return 0; 
    }
    

    你可以使用removeChar() 两次; 1. 使用 removeChar(str, '.'); 和 2. 使用 removeChar(str,':') 删除字符串中的点和冒号。

    此外,您还可以第三次使用 removeChar(str, ';'); 来删除分号。

    您的代码将如下所示:

    #include <bits/stdc++.h> 
    using namespace std; 
    
    void removeChar(char *s, int c){ 
    
        int j, n = strlen(s); 
        for (int i=j=0; i<n; i++)
        {
           if (s[i] != c)
           {
              s[j++] = s[i]; 
           }
        }
    
        s[j] = '\0'; 
    } 
    
    int main() 
    { 
       char ch[100];
       while(scanf("%s[a-z | A-Z ]",ch)!=EOF) 
       {
             removeChar(ch, '.'); 
             removeChar(ch, ':');
             removeChar(ch, ';');
             cout << ch << endl;
       } 
    
       return 0; 
    }
    

    【讨论】:

    • GeeksForGeeks?真的吗?怎么说呢。有些人认为这不是最好的 C++ 站点之一。参见例如“#include using namespace std;”。正确答案由评论者 Sumit 给出
    • @ArminMontigny 结果符合 OP 的要求,一切正常。我承认上述方式可能更容易和更合适,但本教程中提供的技术非常有效。如果有什么通常被弃用,请明确指出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多