You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
3 Hrs
24 Min
45 Seg
Curso de C++ Básico

Curso de C++ Básico

Diana Martínez

Diana Martínez

La biblioteca estandar de C++

17/18
Resources

What is the C++ standard library?

C++ is a powerful programming language, but to take full advantage of its capabilities, it is vital to understand its standard library. This set of libraries extends the language by allowing us to perform a wide range of tasks, from mathematical operations to string handling. However, unlike other programming languages, C++ does not include certain functionality within its core. This is where the standard library comes into play, which we must import as specific libraries.

What are some of the most important libraries?

The C++ standard library includes a variety of fundamental libraries, each with different functions:

  • IOStream: This is essential for data input and output in our programs. We have already used it to print results and capture user information.
  • String: It provides us with string handling, something that, although essential, is not part of the core of the language; we will use it extensively to manipulate text.
  • Other libraries: There are also libraries focused on error handling, advanced mathematical operations and even for working with arrays and data vectors.

How are strings handled in C++?

Before you can work efficiently with strings in C++, you need to integrate the string library that provides the necessary data type:

#include <iostream>#include <string>
int main() { std::string text = "Hello world"; std::cout << text << std::endl; return 0;}

What are the advantages of using std::string?

  • Friendly syntax: By using std::string, you avoid the complexity of handling lists of characters(char[]), making the code cleaner and easier to understand.
  • Additional features: It allows you to use methods such as .size() to quickly know the length of a string, simplifying what in other languages can be a more complex operation.

How to convert strings to numbers?

Imagine that you capture user information that includes numbers and you want to operate on them mathematically. C++ provides us with useful functions within the string library to accomplish this:

  • Conversion to integer:

    int number = std::stoi("10");
  • Conversion to float:

    float numberFloat = std::stof("10.5");

These functions help transform strings representing numbers into numeric data with which you can perform calculations and algebraic operations.

What are the limitations and how to overcome them?

Although the use of the string library makes it easier to work with text, and the conversion functions help to handle numeric data, it is essential to watch out for common errors, such as failed conversions. Be sure to catch and handle exceptions properly to avoid problems in your programming logic. In addition, I encourage you to discover other features of the C++ libraries and practice by developing small projects. By exploring and experimenting, you will improve your skills and confidence in handling this robust language.

Contributions 16

Questions 9

Sort by:

Want to see more contributions, questions and answers from the community?

Librerías estándar de C++:

iostream:

Input/Output (entrada/salida) de datos.

cin >> variable;
cout << variable;

string:

Manejo de cadenas de texto.

string str ("Hola a todos!");
str.pop_back(); // Borra el último carácter de la string

cmath:

Funciones matemáticas comunes como la potencia base^(exponente) en c++:

pow(base, exponente);

exception:

Utilidades para el manejo de errores.

function<int(int,int)> bar;

try {
  cout << bar(10,20) << '\n';
}
catch (bad_function_call& e) // captura la excepción
{
  cout << "ERROR: Esa función está vacía.\n";
}

array:

Manejo de arreglos de datos (matrices de tamaño fijo).

array<int, 0> my_array;   
my_array.empty(); // pregunta si el arreglo está vacío

vector:

Manejo de vectores de datos (representan matrices que pueden cambiar de tamaño).

vector<int> my_vector;
my_vector.push_back (myint); // Agrega un nuevo elemento al final del vector

Este es mi aporte de la clase 😄:

#include <iostream>
#include <string>

using namespace std;

/* Para poder usar cadenas de texto tenemos la libreria string que nos permite hacer cadenas de texto con mayor facilidad */

int main()
{
    string texto = "Hola mundo!";
    cout << texto.size() << endl; /* Así se obtiene el size de la cadena de texto */

    string textonum = "10";
    cout << stoi(textonum) << endl; /* Así se convierte una cadena de texto valido como número, y devuelve  un entero */

    string textoflo = "10.5";
    cout << stof(textoflo) << endl; /* Así se convierte una cadena de texto valido como número flotante, y devuelve un flotante */

}
también esta la biblioteca conio.h para poder usar la función getch() para evitar que el ejecutable se cierre O también stdlib.h para usar el system("cls") para limpiar consola, también system("pause") que funciona como el getch().

Minuto 3:07, la salida por consola está imprimiendo caracteres basura porque no sabe si el conjunto de caracteres ya ha terminado. Para indicarle que una sentencia ha finalizado, es necesario colocar al final de la misma la secuencia de escape \0. Ejemplo:

char texto[] = { 'H', 'o', 'l', 'a', '\0' };

En C++ no hay tipo string, por ello, hay que importarlo de una libreria.

  • iostream: Entrada y salida de datos.
  • string: Manejo de cadenas de texto.
  • cmath: Funciones matematicas comunes.
  • exception: Utilidades para el manejo de errores.
  • array: Manejo de arreglos de datos.
  • vector: Manejo de vectores de datos.

Apunte de la clase: https://towering-lancer-935.notion.site/La-biblioteca-est-ndar-de-C-63e60e90fcfb4559a31bdbaa5727696c
En el apunte esta la lista de funciones que tiene la librería de string

Les dejo el código:

#include <iostream>
#include <string>

using namespace std;

int main() {
  string text = "Hello World";
  cout << text << endl;
  cout << text.size() << endl;
}

Mi aporte:

Null value character

In C/C++ we need to representation the end of string for this reason we have a null character value, we can represent the null value of characters with \0 like that as we can representation the new line value \n
if you don’t use the null value in array of characters the others functions that handdler a string don’t know where are the end of string and posibly continue working with the consecutive values of memory until intersect with any null value

Example

Without null value

  • code
  • output

With null value

  • code
  • output
Excelente explicación

Resumen de las librerias usadas en la clase:

<#include <iostream>
#include <string>
using namespace std;

int main(){
    string texto = "HOLA MUNDO";
    string nEntero = "13";
    string nfloat = "3.14";

    cout << texto <<endl;
    cout << texto.size() <<endl; //saber el numero de caracteres 
    cout << stoi(nEntero) <<endl; //texto a n. entero
    cout << stof(nfloat); // texto a n. flotante
}> 

No pude usar las funcion stof() y stoi() me da el error de que no fueron declaradas en ese scope.

#include <iostream>
#include <string>

using namespace std;

int main(){
    // string texto = "Hola mundo";
    // contar los caracteres
    // cout << texto.size();

    // string texto = "10";
    // transformar string a int
    // cout << stoi(texto) + 1;

    string texto = "10.5";
    // transformar string a int
    cout << stof(texto) + 1;
}

Código de la clase:

#include <iostream>
#include <string> // nos permite declarar un nuevo tipo de dato para las variables
using namespace std;

int main(){
    string texto = "10.4";//esto funciona de escribir texto aunque poco eficiente
    cout << stof(texto)*2;
}

Existe otra forma simple de tener una cadena de texto sin la necesidad de la librería string:

char nombre[] = "Guillermo";

Este modo de asignación, al igual que el expuesto por la profesora, no es más que un arreglo unidimensional que mantiene un tamaño en memoria fijo.