0
votes

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;
}
1
You can use std::isdigit.Anoop Rana
Enter/Return does not end input from std::cin, it just ends a line. Try using std::getline and walking across a std::string.jkb
Try printing your char as an integer as the first line in loop. You might notice something about where you might need to break;. Better way is to get line and ditch the while as jkb said...Abel
Ctrl+D on Linux/Mac, and Ctrl-Z on Windows would send EOF and break the loop. If you redirect input from a file it will also exit when the end of the file is reached.Retired Ninja

1 Answers

0
votes

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;
}

Demo