I need the solve for this problem. Can not understand what to do

72 Views Asked by At

Write a C/C++ program using the following instructions (filename: ID.c/ ID.cpp):
a. Read a file named “program.cpp” (given below).
b. After reading file you have to identify and count the unique name of the variables and name of the preprocessor and print the result.

I have written some code, but it is not correctly identifying the variables and preprocessors. What should I follow or do now?

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
#include <cctype>

using namespace std;

int main()
{
    string filename;
    cout << "Enter filename: ";
    cin >> filename;
    
    ifstream infile(filename.c_str());
    if (!infile)
    {
        cerr << "Error: could not open file " << filename << endl;
        return 1;
    }
    
    map<string, int> variables;
    map<string, int> preprocessors;
    
    string line;
    while (getline(infile, line))
    {
        string::iterator it = line.begin();
        while (it != line.end())
        {
            if (*it == '#')
            {
                string preprocessor;
                ++it;
                while (it != line.end() && !isspace(*it))
                {
                    preprocessor += *it;
                    ++it;
                }
                ++preprocessors[preprocessor];
            }
            else if (isalpha(*it) || *it == '_')
            {
                string variable;
                while (it != line.end() && (isalnum(*it) || *it == '_'))
                {
                    variable += *it;
                    ++it;
                }
                ++variables[variable];
            }
            else
            {
                ++it;
            }
        }
    }
    
    cout << "Variables:" << endl;
    for (map<string, int>::iterator it = variables.begin(); it != variables.end(); ++it)
    {
        cout << it->first << ": " << it->second << endl;
    }
    
    cout << "Preprocessors:" << endl;
    for (map<string, int>::iterator it = preprocessors.begin(); it != preprocessors.end(); ++it)
    {
        cout << it->first << ": " << it->second << endl;
    }
    
    return 0;
}

This is what I tried, and I was expecting a result like below:

Variable-1: a
Variable-2: b
Variable-3: c
Variable-4: d
Variable-5: e
Total number of the variables: 5
Preprocessor-1: include
Preprocessor-2: define
Total number of preprocessor: 2
0

There are 0 best solutions below