OOP244 Project - Milestone1


This article shows some code examples with an idea of each milestone. All examples are just my own idea, it means it is not the only solution and can be wrong. There are a lot of better approaches for solving the problems. Just refer it as one way of ideas. If you have a different one, keep going with that!

Milestone1

1. One way to parse input string to variables.

ex1) intput a line by a textbook.

#include <iostream>
#include <cstring>

std::istream& read(std::istream& is = std::cin) {
    char *s;
    std::string str;

    if (std::getline(is, str)) {
        s = new char[str.length() + 1];
        strcpy(s, str.c_str());
        std::cout << "Your input is: " << s << std::endl;
        delete[] s;
    }
    return is;
}

int main() {
    // 2017/03/12, 12:33
    std::cout << "Enter a date (YYYY/MM/DD, hh:mm): ";
    read();
    return 0;
}

output

Enter a date (YYYY/MM/DD, hh:mm): 2017/03/12, 12:33
Your input is: 2017/03/12, 12:33

@see https://scs.senecac.on.ca/~oop244/pages/content/custo.html (C-Style Example)

ex2) parse formatted input

#include <iostream>
#include <cstring>
#include <cstdio>

std::istream& read(std::istream& is = std::cin) {

    std::string str;

    int y = 0, m = 0, d = 0, h = 0, i = 0;

    if (std::getline(is, str)) {

        int number_of_return = std::sscanf(str.c_str(), "%d/%d/%d, %d:%d", &y, &m, &d, &h, &i);


        std::cout << "ret: " << number_of_return
                << ", y:" << y
                << ", m:" << m
                << ", d:" << d
                << ", h:" << h
                << ", i:" << i
                << std::endl;

    }
    return is;
}

int main() {
    // 2017/03/12, 12:33
    std::cout << "Enter a date (YYYY/MM/DD, hh:mm): ";
    read();
    return 0;
}
output
Enter a date (YYYY/MM/DD, hh:mm): 2017/03/12, 12:33
ret: 5, y:2017, m:3, d:12, h:12, i:33
Enter a date (YYYY/MM/DD, hh:mm): 2017/03/12
ret: 3, y:2017, m:3, d:12, h:0, i:0
Enter a date (YYYY/MM/DD, hh:mm): 
ret: -1, y:0, m:0, d:0, h:0, i:0

@see http://en.cppreference.com/w/cpp/io/c/fscanf

Change number to string


long long n = 112345678900;

std::string s = std::to_string(n);           
// s.length(); 

s.substr(start, length);

@see http://www.cplusplus.com/reference/string/to_string/