How to count strings and integers from an array of strings in C++

1 Answer

0 votes
#include <string>
#include <vector>
#include <iostream>

class Program
{
public:
	int countnum;
	int countstr;
	
	Program() {
        this->countnum = 0;
        this->countstr = 0;
    }

	void count_strings_and_integers(std::vector<std::string> &arr) {
    	int len = arr.size();
    
    	for (int i = 0; i < len; i++) {
    		try {
    			int num = std::stoi(arr[i]);
    			countnum++;
    		}
    		catch (const std::exception& e) {
    			countstr++;
    		}
    	}
    }
    
    void print(void) const {
        std::cout << "Numbers: " << countnum << "\nStrings: " << countstr << std::endl;
    }
};

  
int main() {
    std::vector<std::string> arr = {"java", "888", "9", "c", "python", "109", "c++"};
    
    Program p;

	p.count_strings_and_integers(arr);
	
	p.print();
}



/*
run:
 
Numbers: 3
Strings: 4
   
*/

 



answered Feb 17, 2024 by avibootz

Related questions

1 answer 131 views
1 answer 114 views
1 answer 220 views
1 answer 132 views
...