Home > OS >  How to exit the loop :while(cin>>n) in C
How to exit the loop :while(cin>>n) in C

Time:07-20

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

CodePudding user response:

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(static_cast<unsigned char>(c))){
            
            nums  ;
        }
        else if(std::isalpha(static_cast<unsigned char>(c))){
            chars  ;
            
        }

    }
    std::cout<<"nums: "<<nums<<" chars: "<<chars;
    return 0;
}

Demo

  • Related