【发布时间】:2016-09-09 21:03:02
【问题描述】:
我的任务是从用户那里获取一个没有空格的字符串,并让计算机计算字符、字母、数字和特殊字符的数量(即!@#$%^&*)但是程序似乎是无论该字符属于哪个类别,都跳过第一个字符。请注意,它确实将其计算在字符数中,而不是在其类别中 例子: 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 ;
【问题讨论】:
-
您的变量未初始化,因此可能包含任何内容。初始化时将 i、lett、num 和 spec 设置为 0。
-
a)
'0' ... '9'不是标准 C++ 并且 b) 您需要启用更多编译器警告。 -
我没有看到你在任何地方初始化 i 的值?你不应该在使用它之前将它设置为零吗?
-
@Mojo 这与您的格式无关,而是您在研究和调试尝试中没有表现出足够的努力。
-
@Mojo 这不是关于编程的好坏,而是关于如何提出一个好的问题。这个问题归结为,跳过第一个字母,这里是代码。如果我作为某方面的专家来找你,比如机械师,说这部分漏水,然后你把它翻过来,发现底部有洞,你也会生气。为解决问题付出更多的努力,您将成为一名出色的程序员。
标签: c++ string switch-statement