This is a program that counts how many letters and numbers a string has,but when I Press Enter to exit after entering,it has no response.
#include <iostream>
using namespace std;
int main()
{
char c;
int nums=0,chars=0;
while(cin>>c){
if(c>='0'&&c<='9'){
nums++;
}else if((c>='A'&&c<='Z')||(c>='a'&&c<='z')){
chars++;
}
}
printf("nums:%d\nchars:%d",nums,chars);
return 0;
}
Pressing enter does not end input from std::cin
and std::cin
stops when encountering a whitespace.
Better would be to use std::getline
and std::isdigit
as shown below:
int main()
{
int nums=0,chars=0;
std::string input;
//take input from user
std::getline(std::cin, input);
for(const char&c: input){
if(std::isdigit(c)){
nums++;
}
else if(std::isalpha(c)){
chars++;
}
}
std::cout<<"nums: "<<nums<<" chars: "<<chars;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.