Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

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

...