Questions

Pages: 1234
Hello, I'm new to programming(I'm 14), and there's my very first application...
I've watched some tutorials on youtube(something like 30-40) and then i tried to do some applications with the codes i've seen , i worked like 5-6 hours(I've spend the most part of the time trying to figure out how to solve the errors i've got.)
If you have time , look after the code and tell me where i could do something better , or where i missed something.
And the last thing, tell me what should i learn now.

p,s: Sorry for my bad English.

The debugged App:
http://www37.zippyshare.com/v/29313078/file.html

The codes(I can't paste the code below , because is too long):
http://www37.zippyshare.com/v/82681119/file.html

1
2
  
Last edited on
Ok, I skimmed over and here what I noticed immideately:
1) Non-existent formatting. Formatting your code is important because it allows you to easily get code structure and generally makes code easy to read.

2) Using system(). It is bad. It is slow, it is possible security hole, it is unportable.
Define own clear console function and use it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <windows.h>

void cls()
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coordScreen = { 0, 0 };
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
        return;
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    if( !FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ) ||
        !GetConsoleScreenBufferInfo( hConsole, &csbi ) ||
        !FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
        return;
    SetConsoleCursorPosition( hConsole, coordScreen );
}
If you would want to port your program on other OS, you will need to only make changes to this function.

3) Overuse of goto. Usage of goto implies inability to properly plan program flow. It makes harder to see program structure and harder to make changes.

4) Code duplication. Ideally you should write something only once and then just repeat said code (by calling a function or looping for example).
In your main():
* In first several cout statements:
    - you are outputting number
    - then some operation name
* in switch:
    - selecting operation based on number
    - clearing screen
    - calling some function.
This makes you wonder: couldn't you link number and name/function in some way to use loops in first case and call function by number in second? You actually can. Look at rewritten main:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Additional headers:
#include <vector>
#include <functional>
#include <string>

//...

int main()
{
       //or if you prefer function pointers: void (*)() ↓
    const std::vector<std::pair<std::string, std::function<void(void)>>> menu = { {"", nullptr}, //Dummy to avoid index convertion
        {"Lottery",         Lottery},          {"Money Converting",         moneycalculator},
        {"Age Calculator",  AgeCaluclator},    {"Super Market",             SuperMarket},
        {"Basic Calculator", basicCalculator}, {"Multi-Numbers Calculator", AdvencedCalculator},
    };
    std::cout << "Choose what do you want to do...\n\n";
    for(unsigned i = 1; i < menu.size(); ++i) {
        const int margin = 23;
        const int item_margin = margin - menu[i].first.size() / 2;
        std::cout << std::string(margin - 3/*<-{ length*/, ' ') << "<-{" << i << "}->\n" <<
                     std::string(item_margin, ' ') << menu[i].first << "\n\n";
    }
    int choice;
    std::cin >> choice;
    if(std::cin && choice > 0 && choice <= menu.size()) {
        cls();
        menu[choice].second(); //Call function stored in vector by index "choice"
    }
}
(Also you missed one break statement in your main :P )
Last edited on
closed account (SECMoG1T)
Hi some nice work there looks ...you doing great, I would advice you to get a nice book that would guide you through .
Check out some nice books here

http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list

It would be better that you copy paste your code than providing some links , less people will bother to download and check 'em out, Anyway good luck
Hello MiiNiPa , i have some questions for you, if you don't mind.

This Void Cls , it's practically an "customed" System("cls") Who improves performances and stability ? And if yes, how can i put it in mt actually project(how can i make it work).

Can you tell me an alternative of goto ? Or something like goto.

I always was thinking, if i made an integer in a Void, can i include it in another void , or main ?

And about the rewritten main , well i don't understand..
Anyway, when i try to run it i got:
Function is not a member of std
Template argument is invalid
And expected } , ; etc.


I must edit something ?
Last edited on
This Void Cls , it's practically an "customed" System("cls") Who improves performances and stability ?
Yes. You just need to include windows.h and place function definition before first use.

Can you tell me an alternative of goto ?
while {} / do {} while;. Additionally you can decompose your function in several to make those loops easier to use. (Examples will follow later after I fix some other function in your program)

I always was thinking, if i made an integer in a Void, can i include it in another void , or main ?
I do not think I understand you. Can you clarify what you mean? An example maybe?

Anyway, when i try to run it i got:
Function is not a member of std
Template argument is invalid
And expected } , ; etc.
I must edit something ?
You need to include headers at the beginning. Also make sure that your compiler is in C++11 mode. If you say what IDE do you use, I might help you.
For the include part..

I mean ... let's just do this.

I make a void name icecream.

Void icecream {
int icecream = 69;
}

int main {
cout << icecream
}
Can i do that somehow ?
-----

I actually don't know what compiler i have , i don't even remember when i installed it.

Where i can go to see what compiler i use ?
(I included headers )
Use return values:
1
2
3
4
5
6
7
8
9
int icecream()
{
    return 69;
}

int main()
{
    std::cout << icecream(); //Call function and output result
}


I actually don't know what compiler i have
Which program do you use to compile your programs? What is written in window header?


Example of avoiding goto:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
bool ask(std::string question)
{
    std::cout << question << '\n';
    char c;
    do {
        std::cin >> c;
        c = tolower(c);
        if(c != 'y' && c != 'n')
            std::cout << "Invalid answer. Only Y, y, N and n is allowed\n";
    } while(c != 'y' && c != 'n');
    return c == 'y';
}


void basicCalculator_impl()
{
    static const std::vector<std::function<int(int, int)>> op = {
        std::plus<int>(), std::minus<int>(), std::multiplies<int>(), std::divides<int>(),
    };
    std::cout << "Enter first number\n";
    int first;
    std::cin >> first;
    std::cout << "Enter second number\n";
    int second;
    std::cin >> second;
    std::cout << "Choose the type (0 = + | 1 = - | 2 = * | 3 = / |)\n";
    int type;
    std::cin >> type;
    if(std::cin && type >= 0 && type <= 3)
        std::cout << "Your number is: " << op[type](first, second) << '\n';
    else
        std::cout << "Please write 0 ,1, 2 or 3\n";
}


void basicCalculator()
{
    do {
        cls();
        basicCalculator_impl();
    } while(ask("Do you want to continue?"));
}
I noticed something , why are you typing "std::" ?
If you use "using namespace std;" you have some disadvantages ?

Anyway , i use CodeBlocks Ide , i think..

Here's a photo: http://i.imgur.com/h1LU7Sy.png
If you use "using namespace std;" you have some disadvantages ?
Yes. Like silently calling wrong function.
http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

Anyway , i use CodeBlocks Ide , i think..
Yes. It is Code::Blocks. To turn on C++11 go to SettingsCompiler and check Have g++ follow the C++11 ISO C++ language standard
Tomorrow i will try your codes.
Last edited on
Did a (very basic) rewrite trying to save original behavior and output as much as possible (fixed obvious bugs and changed output where I felt lazy to program exact same output)
http://pastebin.com/bNF4vtBa

I turned on C++ 11, and then used your Void cls() , and it worked perfectly.
I have some questions...

I will use from now "std::" , and i need to know for what commands i must put it , i observed as 'int" does not require "std::", but cout , cin.

In your remake of my program i saw a lots of commands , who i don't know.Can you explain to me ?

template <typename T>

T read(const std::string& request)

T value;

bool repeat = true; // I used just one time bool, but i forgot what actually is he doing.

return value; // What is she returning? What value.

bool ask(const std::string& question)
{
std::cout << question << '\n';
char c;
do {
c = tolower(read<char>(""));
if(c != 'y' && c != 'n')
std::cout << "Invalid answer. Only Y, y, N and n are allowed\n";
} while(c != 'y' && c != 'n');
return c == 'y';
}

Only Y,y,N and n are allowed , what is that ?



static const std::vector<std::pair<std::string, double>> goods = { {"", -1.0},


void moneycalculator_impl()

_impl , what is that for ?


static std::mt19937 rg(time(nullptr));
static std::uniform_int_distribution<> dist(1, 6);



int year = read<int>

What is read doing?


I see your programing very complicated..




Last edited on
I will use from now "std::" , and i need to know for what commands i must put it
For those names which are part of standard library and not part of base language.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//This is a template declaration.
//All entries of T will be replaced by whatever type we provide.
//http://www.cprogramming.com/tutorial/templated_functions.html
//http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part
template <typename T>
T read(const std::string& request)
{
    //Declare variable value of type T
    //So for read<int>(""); it would be int value
    T value;

    //Booleans have two values: true or false.
    //Used as part of conditions
    bool repeat = true; 
/*...*/
    //returning value we declared at the beginning of function and read in skipped part
    return value; 
}
int year = read<int>
What is read doing?
It calls read() function declared before with template parameter T replaced with int.

void moneycalculator_impl()
_impl , what is that for ?
Short for implementation. It is just part of the name. I separated most function in two: one (_impl) which actually doing something once, and second which calls first in a loop.
Only Y,y,N and n are allowed , what is that ?
It is a helper function which ask a question and return boolean which stores if ansver was positive (Yes, Y) or negative (No, N). I just decided to forbid other answers.

static std::mt19937 rg(time(nullptr));
static std::uniform_int_distribution<> dist(1, 6);
This is just part of random library in C++. As de-facto srand/rand is deprecated and not advised to use, I used C++11 alternative.
http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
I declared it static so generator will be shared by all function calls and not be reseeded each call.


I see your programing very complicated..
It is actually pretty basic. Only advanced parts migh be storing functions in containers (main and bot calculators), but again, function pointers are usually learned with normal poointers and in C you run into them as soon as you need to sort something.


Main motto of programming: if you need to write something more than once, you are doing it wrong. Write repetitive code parts once, and callthem later with diifferent parameters.
I was trying to do an simple register and log in program , i think it's working fine, but the only problem is , it only work with numbers..When i'm typing anything else , simply run all my commands.

The cause ?


Code:http://pastebin.com/6WPJEPDZ
Well, you said compiler to read number and it expect to read number, not letters. If it cannot read proper input, it sets stream state to failure (causing all subsequent reads to fail as well), and leaves offending data in input buffer (next read will read same date again). You need: reset stream state, so it would work properly again; skip incorrect data; ask to input again.
http://www.cplusplus.com/forum/general/149655/

My read() function from before actually did that: ask for input, and repeat if input was incorrect.
Last edited on

I did something, now when i try to write letters it run this part of code..

if(reg==1)
{
cls();
regis();

}
else
{

cls();
std::cout<<"You haven't entered 1, please try again\n";
main();

}


}



Can you tell me how to restart the stream state ?
When you write something unexpected, variable either is unchanged or set to 0 depending on standard version.

Can you tell me how to restart the stream state ?
Here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int i;
//std::cin >> i;
//if (!std::cin)
if( ! (std::cin >> i)) { //If input failed
    //Clear stream state
    std::cin.clear(); 

    //Deal with wrong input:

    //Skips all input till the end of the line
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    //Or, alternative: Skips only one chunk of input
    //while(!isspace(std::cin.get()))
    //    ; 
}
//http://www.cplusplus.com/forum/general/149655/#msg782371 
Wrap it in while loop if you want to user to re-enter value.
Well , the code won't work...

But, I did that..

std::string user,pass;
std::string user1,pass1;

And then it worked with numbers and letters.
Well , the code won't work...
It works. Did you include all needed headers?
std::string user,pass;
And then it worked with numbers and letters.
It works if you need input as string. If you need it as integer (to use it in calculations for example), it is not enough.
It works if you need input as string. If you need it as integer (to use it in calculations for example), it is not enough.

Well..It works.

I think the program is finished, can you try it for me? and then tell me if it's ok..
http://pastebin.com/M1HZV44C

And one question, can i from a console application link to a site ?
Last edited on
Pages: 1234