Tag Archives: #007000

Mastery 27

Validated user input in C++

For this mastery, I found  a super useful video that taught me how to make a validation for a user input

Here is also an example code with a validation user input code:

 

 
 

int main(){
    bool valid = false;
    int input;
    while(!valid){
        if(std::cin>>input){//this checks whether an integer was entered
            if(input  0) valid = true;//then we have to see if this integer is in range
        }else std::cin.clear();//some cleaning up
		
        std::cin.ignore(std::numeric_limits<:streamsize>::max(), 'n');//empty input stream

        if(!valid) std::cout "this input is not validn";
    }
    std::cout " is between 1 and 5n";
    std::cin.get();
    return 0;
}

 

Credits:

https://www.youtube.com/watch?v=YIX7UhIKEIk

1017 27

Mastery 23

Creation and use of vectors in C++

Vector

 

Vectors are sequence containers representing arrays that can change in size.

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

Example

Output:

Credits:

http://www.cplusplus.com/reference/vector/vector/vector/

http://www.cplusplus.com/reference/vector/vector/

1017 23

Mastery 12

Creating functions in C++

Functions

Functions allow to structure programs in segments of code to perform individual tasks.

In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is:

type name ( parameter1, parameter2, ...) { statements }

Where:
– type is the type of the value returned by the function.
– name is the identifier by which the function can be called.
– parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example:int x), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
– statements is the function’s body. It is a block of statements surrounded by braces { } that specify what the function actually does.

 

 

// function example
 <iostream>
using namespace std;

int subtraction (int a, int b)
{
  int r;
  r=a-b;
  return r;
}

int main ()
{
  int x=5, y=3, z;
  z = subtraction (7,2);
  cout << "The first result is " << z << 'n';
  cout << "The second result is " << subtraction (7,2) << 'n';
  cout << "The third result is " << subtraction (x,y) << 'n';
  z= 4 + subtraction (x,y);
  cout << "The fourth result is " << z << 'n';
}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6

Mastery 10

Basic output (printing) and inpur (text based) in C++

The standard library defines a handful of stream objects that can be used to access what are considered the standard sources and destinations of characters by the environment where the program runs:

stream description
cin standard input stream
cout standard output stream
cerr standard error (output) stream
clog standard logging (output) stream

Standard output (cout)

On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.

For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two “less than” signs).

cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the value of x on screen  

Standard input (cin)

In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin.

For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data is stored. For example:

int age;
cin >> age;

Basic output and input in C++

(Tutorial en español, ,PIW)

Para este tutorial es necesario por lo menos saber la estructura de un programa que lo puedes checar en este link: http://www.cplusplus.com/doc/tutorial/program_structure/

Las funciones de Input and Output son funciones que se ponen para poder tanto poner o imprimir informacion en pantalla y con otro el poder recibir informacion del usuario al programa.

OUTPUT

Esta funcion de C++ es una funcion que te permite imprimir informacion hacia el usuario. La funcion que se utiliza puede ser de dos maneras, pero la mas facil y mas usado es cout que es una impresion de informacion estandar que despues de usar ese cout se utiliza dos simbolos de << que quiere decir una insercion o lo que va despues de, por ejemplo: 

 

1
2
cout << "Hello";  // prints Hello
cout << Hello;    // prints the content of variable Hello 
 

donde estos simbolos señalan lo que sigue y tambien por ejemplo: 

cout << "I am " << age << " years old and my zipcode is " << zipcode;
 

donde al finalizar de poner todo lo que se quiere anhidar y decir se pone un ; para terminar esa accion.

INPUT

Esta otra funcion de C++ es una funcion que permite recibir informacion que el usuario tecle para introducirla en el programa para asignar el valor a una variable. Este comande es el de cin que se utiliza igual con un simbolo que es el de >> que es el contrario del output, con esto quiere decir que el valor que ponga el usuario. Un ejemplo de esto es: 

1
2
int age;
cin >> age;
 

Pero tambien para esto necesitas declarar las variables que van a recibir algun tipo de valor ya sea string(texto), int(entero), float(numeros decimales), char(caracteres). Y al finalizar tambien se pone un ; para finalizar esa accion.

Si requieren mas informacion visiten esta pagina: http://www.cplusplus.com/doc/tutorial/basic_io/ que es donde me base para hacer este tutorial en español.