Tuesday, March 28, 2023

Coding Challenge #35

 // from Coursera's course "C for Everyone: Programming Fundamentals", week 5 peer graded assignment
// goal was to read a file to get the weights of elephant seals, then find the average of the weights.
// the file is space-tab sperated (ikr, what?). so a line would look like...
// 1234     4321     6123     1563
// and it would also be line-separated (as displayed in my browser) so... yeah.
#include<stdio.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// so the seal file when i read it was (space+tab) separated... ok *shrug*
// turn the raw file string into a vector of int's
std::vector<int> separateValues(std::string rawString){
    std::vector<int> v;
    std::string tmp = "";
    for(int xint = 0, len = rawString.length();xint < len;xint++){
        if(rawString[xint] == ' ' && (xint+1) < len && rawString[xint+1] == '\t'){ // space followed by tab; end of current value
            try{
                v.push_back(stoi(tmp)); // turn string value into number
            }catch(...){
                cout << "Exception: it was probably that the file ends in a space and therefore the resulting string is not a number." << endl;
            }
            tmp = ""; // empty string buffer
            xint++; // don't forget to skip tab by forwarding xint
        }else tmp += rawString[xint];
    }
    if(tmp != ""){
        try{
            v.push_back(stoi(tmp)); // turn string value into number
        }catch(...){
            cout << "Exception: it was probably that the file ends in a space and therefore the resulting string is not a number." << endl;
        }
    }
    return v;
}
int main(void)
{
    std::string wholeFile = "";
    /*
    // so, awkward... but i don't actually have the file to read.
    // i'll just pretend like i'm reading it.
    // to enable this to compile (onlinegdb.com,etc), i've commented-out this section
    #include <fstream>
    ifstream ifs;
    ifs.open("myData.tsv");
    if (!ifs.is_open()){ // check it was opened; to prevent infinite hdd-reading loop without yield. Oh, C++, you rascal ;)
        cout << "Error; file could not be opened." << endl;
        ifs.close();
        return 1;
    }
    std::string buffer;
    while(!ifs.eof()){ getline(ifs,buffer); wholeFile += buffer; }
    ifs.close();
    */
    std::vector<int> v = separateValues(wholeFile);
    int avg = 0;
    int total = 0;
    for(int xint = 0, len = v.size();xint < len;xint++)
        total += v[xint];
    
    if(v.size() > 0) avg = total / v.size(); // payload: get the average. don't divide by 0 :/
    
    cout << "Your average, sir: " << avg << endl;


return 0;
}

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...