Shajahan Shaik
Shajahan Shaik

Reputation: 1

How do I separate chars and integers from a string/file?

Assume that we are given input file in the following form:

12 a -5 
T 23 -1 34 R K s 3 4 r  
a a 34 12 -12 y 

Now, we need to read the entire file and print the following:

number of integers
number of lowercase char
number of uppercase char
sum of all integers

Questions like this have always been a thorn in my flesh and I want to get this over with once and for all.

Upvotes: 0

Views: 80

Answers (3)

ChrisD
ChrisD

Reputation: 674

Basically you want to parse the command line, open the file, parse each line token by token, and check the requirements for each token. I hope this helps.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdlib.h>

using namespace std;

int main(int argc, char* argv[]) {
        ifstream in(argv[1]);
        string line, ch;
        int int_count = 0, upper_count = 0, lower_count = 0, sum = 0;
        /* Grab each line from file and place contents into line */
        while(getline(in, line)) {
                istringstream ss(line);
                /* Parse each token in line */
                while(ss >> ch) {
                        /* Is it a digit? */
                        if(isdigit(ch[0])) {
                                int_count++;
                                sum += atoi(ch.c_str());
                        }
                        /* If it's not, then it must be a char */
                        else {
                                if(isupper(ch[0]))
                                        upper_count++;
                                else
                                        lower_count++;
                        }
                }
        }
        in.close();

        cout << "Number of integers: " << int_count << endl;
        cout << "Number of lowercase char: " << lower_count << endl;
        cout << "Number of uppercase char: " << upper_count << endl;
        cout << "Sum of all integers: " << sum << endl;

        return 0;
}

Upvotes: 1

Patrick
Patrick

Reputation: 131

  1. Split by space

  2. Check that it contains only 0-9, '-' and '.', if it does, it's probably a number. If it doesn't; probably some text.

  3. Tally up as you go along.

Upvotes: 0

paulsm4
paulsm4

Reputation: 121599

You need to parse the file:

1) separate raw text into tokens, then

2) "decide" if the token is a string, an integer, or "something else".

3) Count the results (#/integers, #/strings, etc)

Here's an example: Parse A Text File In C++

Here's the canonical textbook on the subject: The Dragon Book

Upvotes: 0

Related Questions