Here's the C++ code i did for myself:

#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <string>
#include <cctype>
void terminate()
{
    const unsigned short SEC = 5; // constant for 5 times
    std::cout << "\nProgram will close in,\n"; // print
    for (int c=SEC; c>=0; c--) {
        if (c==0) { // if c equal with 0
            exit(EXIT_SUCCESS); // close the console
        }
        else { // if c not reach 0
            std::cout << c << " "; // print the value one by one
        }
        // system clock
        clock_t start = clock();
        clock_t end = CLOCKS_PER_SEC;
        while ((clock()-start) < end) {}
    }
}
int main()
{
    const unsigned short size = 5;
    double n[size];
    std::ofstream fout; // creating object for output file
    // get the number to assign to each array
    for (int c=0; c<size; c++) {
        std::cout << "Enter number #" << c+1 << ": ";
        (std::cin >> n[c]).get();
    }
    fout.open("b4sort.txt"); // create a file #1
    fout << "Number before sorting:\n"; // print output on the file #1
    for (int c=0; c<size; c++) {
        fout << n[c] << ", ";
    }
    fout.close(); // close that file
    // sorting
    for (int c=0; c<size-1; c++) {
        for (int d=0; d<size-1-c; d++) {
            if (n[d] > n[d+1]) { // swapping
                double temp;
                temp = n[d];
                n[d] = n[d+1];
                n[d+1] = temp;
            }
        }
    }
    fout.open("aftersort.txt"); // create a new file #2
    fout << "Number after sorting:\n"; // print output on the file #2
    for (int c=0; c<size; c++) {
        fout << n[c] << ", ";
    }
    fout.close(); // close file #2
    char filename[300]; // declare a string variable
    char read; // declare a char variable
    long alphabetic = 0; // alphabetic count value
    long digit = 0; // digit count value
    long punctuation = 0; // punctuation count value
    long spacing = 0; // spacing count value
    long unknown = 0; // unknown count value
    std::ifstream fin; // creating object for input file
    std::cout << "\n\nTo analysis each text now.\n"; // display this
    std::cout << "Enter filename: "; // ask user to enter a filename
    std::cin.getline(filename, 300);
    fin.open(filename); // opening the file
    if (fin.is_open()==false) { // if cannot open the file
        std::cout << "\nOpen file = 0"; // the file can't be open
    }
    else { // else, the file can be open
        fin.get(read); // read char one by one
        while (fin.good()==true) { // test and get each character one by one
            if (isalpha(read)) { // if the char is alphabetic
                ++alphabetic;
            }
            else if (isdigit(read)) { // if the char is numeric
                ++digit;
            }
            else if (ispunct(read)) { // if the char is punctuation
                ++punctuation;
            }
            else if (isspace(read)) { // if the char is space
                ++spacing;
            }
            else { // if the char is unknown character
                ++unknown;
            }
            fin.get(read); // get next character and test
        }
    }
    fout.close(); // close the file
    fout.open("textanalysis.odt"); // create a new file
    // print on the new file
    fout << filename << " text analysis.\n";
    fout << "\nTotal: " << alphabetic+digit+punctuation+spacing+unknown << std::endl;
    fout << "Alphabetic: " << alphabetic << std::endl;
    fout << "Digit: " << digit << std::endl;
    fout << "Punctuation: " << punctuation << std::endl;
    fout << "Spacing: " << spacing << std::endl;
    fout << "Unknown: " << unknown << std:: endl;
    fout << "\nFinish!";
    fout.close(); // close that file
    terminate(); // invoke function to close console
    return 0;
}

can someone show me how to turn this code into the small parts (function) one bye one, especially for that sorting and swapping parts.

sory for my bad english and i'm just a beginner in C++...

Dani AI

Generated

Good instincts: split the program into small, single-purpose functions (reading, printing, sorting, analyzing, writing results, and a short wait/exit). was right to recommend using size_t for sizes and moving the sort into its own function, but a quick clarification on the array/pointer point: when you declare a function parameter like double arr[] it decays to a pointer (double*) — it is not a true C++ reference to the array. If you want fixed-size-array-by-reference use either std::array/std::vector or the reference-to-array syntax or templates.

Suggested top-level function split (prototypes):

#include <vector>
#include <string>

std::vector<double> read_numbers(std::size_t count);
void write_numbers(const std::vector<double>& nums, const std::string& filename, const std::string& header);
void sort_numbers(std::vector<double>& nums);       // implement with std::sort or a local bubble-sort for learning
struct Counts { std::size_t alpha, digit, punct, space, other; };
Counts analyze_file(const std::string& filename);
void write_analysis(const std::string& filename, const Counts& c);
void wait_then_exit(unsigned seconds);

Sorting and swapping tips: for production use std::sort(nums.begin(), nums.end()) (fast and concise). If you keep a manual bubble sort for learning, extract swapping to std::swap(nums[i], nums[i+1]) so the swapping logic is a single simple call and less error-prone. Remember to use std::size_t for indexes and be careful with loop bounds (off-by-one mistakes are the usual bug).

File-analysis and input robustness: prefer std::string for filenames and std::getline(std::cin, filename). Read characters using while (fin.get(ch)) and always cast to unsigned char before calling std::isalpha/std::isdigit/etc to avoid undefined behavior on negative char values:

char ch;
Counts cnt{};
while (fin.get(ch)) {
    unsigned char uc = static_cast<unsigned char>(ch);
    if (std::isalpha(uc)) ++cnt.alpha;
    else if (std::isdigit(uc)) ++cnt.digit;
    else if (std::ispunct(uc)) ++cnt.punct;
    else if (std::isspace(uc)) ++cnt.space;
    else ++cnt.other;
}

Small troubleshooting checklist: check every file open with if (!fin)/if (!fout), avoid busy-wait timing loops (use std::this_thread::sleep_for), clear input with std::cin.ignore(...) after numeric input, and double-check you close the correct stream (in the posted code there is a likely spot where fout.close() was called when fin.close() was intended). Refactor one function at a time, test each piece, and you’ll get there quickly.

Recommended Answers

All 4 Replies

i grab it from my friend, and he ask me to make it in function, it took me a very long hours to understand this code, and then i put the comments myself to help someone understand like mine also... c++ very hard to learn.

Look at the functional blocks first, those are candidates for refactoring into separate functions. For example, the sort block:

// sorting
    for (int c=0; c<size-1; c++) {
        for (int d=0; d<size-1-c; d++) {
            if (n[d] > n[d+1]) { // swapping
                double temp;
                temp = n[d];
                n[d] = n[d+1];
                n[d+1] = temp;
            }
        }
    }

can be turned into a function very easily - let's call it sort_doubles():

void sort_doubles( double n[], size_t size )
{
    // sorting
    for (size_t c=0; c<size-1; c++) {
        for (size_t d=0; d<size-1-c; d++) {
            if (n[d] > n[d+1]) { // swapping
                double temp;
                temp = n[d];
                n[d] = n[d+1];
                n[d+1] = temp;
            }
        }
    }
}

Notice that I changed the loop variables c and d to size_t instead of int. That is because array indexes are size_t types. Also, the array parameter passed to the function is by default by reference in C++, so sorting the array in the function, results in the passed array getting sorted - they are one and the same. So, that block of code in your code for sorting the array is now replaced with this single line:

sort_doubles(n, size);

Note that you should also change the type of size from const unsigned short to either a size_t or const size_t. Making it const really doesn't do anything for you in this case. That would be more useful for global or external variables, but unnecessary here.

thank you rubberman...
i understand now..
the function header -> void sort_doubles( double n[], size_t size ) also same like this:
void sort_doubles( double* pN, size_t size ), isnt it? because when we pass an array we actually pass a pointer?

Actually, in C the pointer analogy is correct. However, in C++, it actually is passed as a reference to the array. Functionally the same, semantically subtlety different. In any case. The nice thing about references is that you don't need to verify that the passed pointer is not null... the compiler deals with that for you mostly, and when it doesn't, runtime exceptions allow you to "catch" such problems much more easily. So, do get into the habit of (judiciously) using exception handling in your code. Too much is counter productive. Too little leads to system crashes. Just enough allows you to intelligently recover from may errors, or terminate the program in a much more controlled manner than a simple core dump.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.