C ++初学者,switch并没有输出字符串的第一个字符

时间:2016-09-09 21:03:03

标签: c++ string switch-statement

我的任务是获取一个没有用户空格的字符串,并使计算机计算字符,字母,数字和特殊字符的数量(即!@#$%^& *)但是程序似乎无论这个角色属于哪个类别,都要跳过第一个角色。请注意,它确实将其计入不属于其类别的字符数 例: cin>> AZ12!@

输出:6个字符,1个字母,2个数字,2个特殊字符。 它总是跳过第一个角色。

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

int main()
{
    char str[100]; // available character string max is 99 characters
    int i;
    int lett;
    int num;
    int spec;

    cout << "Please enter a continuous string of characters with no spaces" << endl ;
    cout << "(example: ASO@23iow$)" << endl << endl ;   //shows an example and then adds a blank line
    cout << "Enter your string: " ;
    cin >> str ;
    cout << endl ;

   while(str[i] != 0)
   {
      switch(str[i])
       {
            case '0' ... '9':
                i++ && num++;
                break ;
            case 'a' ... 'z':
                i++ && lett++;
                break ;
            case 'A' ... 'Z':
                i++ && lett++;
                break ;
            default :
                i++ && spec++;
       }
   }

   cout << "your string has " << i << " characters" << endl ;
   //prints the number of numbers in the string
   cout << "Your string has " << num  << " numbers in it." << endl ;       
   cout << "Your string has " << lett << " letters in it." << endl ;
   cout << "Your string has " << spec << " special characters." << endl   ;
   return 0 ;

1 个答案:

答案 0 :(得分:0)

在您的代码中,int i未初始化。使用它是未定义的行为

int i = 0;

其他变量也是如此。 这也没有你认为它做的事情:

i++ && lett++;

这不是做两个操作,它是一个布尔运算符。它使用了一种称为短路的东西,这意味着如果&&的第一部分评估为假(即0),则表达式必须为0,因此评估其余部分(即{{}时没有意义1}}部分)。因此,对于您的第一个循环(lett++),您的i == 0将被短路。

将这些更改为:

lett++

如果你解决了这个问题,它会起作用:

Live example