Vectores, Strings y Ficheros en C++: Referencia Práctica de Programación
Vectores
#include <vector>
- Cambia dinámicamente su tamaño =>
v.resize(4); - Añade un valor al final del vector =>
v.push_back(12); - Borrado de un elemento en la posición pos =>
v.erase( v.begin()+pos ); - Borrado de todo el vector =>
v.clear(); - Obtener el último elemento =>
int ultimo = v.back(); - Eliminar el último elemento =>
v.pop_back();
Strings
- Lectura con delimitador:
getline(cin, cadena, ','); - Recorrido de un string:
for (unsigned int i = 0; i < s.length(); i++) - String a vector de caracteres =>
strcpy(cad, s.c_str()); - Entero a string =>
#include <sstream>
int n = 100; stringstream ss; ss << n; string numero = ss.str(); - String a entero =>
string numero = "100"; int n = atoi(numero.c_str());
Ficheros de texto
- Declaración de flujo de lectura:
ifstream fich_leer; - Apertura:
fichero.open(nombre, ios::in); // fichero.open(fich_name.c_str(), ios::in) - Lectura por líneas =>
string s; while (getline(fi, s)) { // hacer algo con 's' } - Lectura de más de una variable =>
while (fichero >> linea) { ... } - Ejemplo de procesamiento de palabras de un tweet:
while (getline(fich, tweet)) { // Cogemos el tweet stringstream ss(tweet); // Stringstream ss de tweet while (ss >> palabra) { // Cogemos palabra por palabra // ... } } - Escritura en un fichero de texto =>
ficheroW << ship.fighters[i].type << " (v";
Ficheros binarios
- Apertura en modo binario =>
fichero.open(nombre, ios::in | ios::binary); - Lectura de un fichero binario =>
while (fichero.read((char *)&fighterB, sizeof(fighterB))) { fighter.velocity = fighterB.velocity; fighter.attack = fighterB.attack; ship.fighters.push_back(fighter); } - Acceso directo a un elemento =>
fbl.seekg((3 - 1) * sizeof(ciudad), ios::beg);
fbl.read((char *)&ciudad, sizeof(ciudad));(usarseekppara escritura) - Escritura de un fichero binario =>
strncpy(fighterB.type, FIGHTERABR[option].c_str(), 2); fighterB.type[2] = '\0'; fighterB.cost = ship.fighters[i].cost; ficheroW.write((const char *)&fighterB, sizeof(fighterB));
Argumentos
- Firma de
main:int main(int argc, char *argv[]) - Comprobación de una opción:
if (!strcmp(argv[i], "-l"))
Modular
- Protección de cabeceras:
#ifndef _m_ // #define _m_ // #endif
POO
- Sobrecarga del operador de salida:
ostream& operator<<(ostream &os, const Planet &p) { os << p.name << " (" << p.sector << "), " << p.letter << p.number << endl; return os; }