【问题标题】:string,char comparison in c++C++中的字符串,字符比较
【发布时间】:2013-03-21 23:52:15
【问题描述】:

*你好! 我正在制作用户输入句子和程序的程序 打印出一个句子中有多少个字母(大写和非大写)。 我做了一个程序,但它打印出奇怪的结果。请尽快提供帮助。 :)

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

int main()
  {
string Sent;

 cout << "Enter a sentence !"<<endl;
 cin>>Sent;

    for(int a=0;a<Sent.length();a++){

        if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){
           cout << "this is letter"<< endl;
        }else{
            cout << "this is not letter"<< endl;
        }

    }



}

【问题讨论】:

  • a&lt;b&lt;c: C++ 不能那样工作。
  • 能否请您附加“奇怪的结果”?

标签: c++ string char ascii string-comparison


【解决方案1】:

首先你会得到一个而且只有一个词。 cin &gt;&gt; Sent 不会提取整行。您必须使用getline 才能执行此操作。

其次,您应该使用isspaceisalpha 来检查字符是否为空格/字母数字符号。

第三,a &lt; b &lt; c 本质上与(a &lt; b) &lt; c 相同,这根本不是您的意思(a &lt; b &amp;&amp; b &lt; c)。

【讨论】:

    【解决方案2】:

    您可以使用 std::alpha: 执行以下操作

    #include <iostream>
    #include <string>
    #include <cctype> 
    using namespace std;
    
    int main()
    {
       string Sent;
    
        cout << "Enter a sentence !"<<endl;
        //cin >> Sent;
        std::getline (std::cin,Sent);
        int count = 0;
    
         for(int a=0;a<Sent.length();a++){
            if (isalpha(Sent[a])
            {
              count ++;
             }
          }
          cout << "total number of chars " << count <<endl;
    
      }
    

    如果您的输入包含空格,使用getline 比使用cin&gt;&gt; 更好。

    【讨论】:

    • “如果您的输入包含空格,则使用 getline 比使用 cin 更好。” 不。最好使用getline on cin,因为operator&gt;&gt; 在空格处停止。两者都在cin 上运行;)。
    【解决方案3】:
    if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){
    

    这是错误的。您无法使用此表示法进行比较。 你必须这样做:

    if( Sent[a] > 96 && Sent[a] < 122 || ....
    

    【讨论】:

      【解决方案4】:
      if (96 < Sent[a] && Sent[a]<123 || 64 < Sent[a] && Sent[a]<91)
      

      这就是你想要的,因为:

      96<int(Sent[a])<123
      

      96&lt;int(Sent[a]), 评估为布尔值,然后将其(即 0 或 1)与 123 进行比较。

      【讨论】:

        【解决方案5】:

        这一行

        if (96&lt;int(Sent[a])&lt;123 || 64&lt;int(Sent[a])&lt;91)

        一定是这样的

        if ((96&lt;int(Sent[a]) &amp;&amp; int(Sent[a])&lt;123) || (64&lt;int(Sent[a]) &amp;&amp; int(Sent[a])&lt;91))

        但我建议使用cctype 头文件中定义的函数isalpha()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-19
          • 2016-02-08
          • 2013-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多