AQUI LES DEJO EL LINK DEL VIDEO DONDE EXPLICO
https:/
#Mastery28
#TC1014
AQUI LES DEJO EL LINK DEL VIDEO DONDE EXPLICO
https:/
#Mastery28
#TC1014
Comments Off on User input (text based) in Python (basic)
Posted in Blogs, Syndicated, TC1014 Blogs
Tagged #mastery28, #TC, #TC1014, Mastery
Para manejar archivos dentro de c++ tenemos que utilizar el archivo de cabecera fstream.h. Este define las clases ifstream, ostream y fstream para poder realizar operaciones de lectura, escritura y lectura/escritura en archivos respectivamente. Para trabajar con archivos se tienen que crear objetos de éstas clases, según las operaciones que deseamos efectuar. Iniciaremos con las operaciones de escritura, para esto tenemos que declarar un objeto de la clase ofstream, después utilizaremos la función miembro open para abrir el archivo, escribimos en el archivo los datos que sean necesarios utilizando el operador de inserción y por último cerramos el archivo por medio de la función miembro close, como podemos ver en el siguiente ejemplo:
#ff8000; background-color: #fafafa;”>#include
int main()
{
ofstream archivo; #ff8000; background-color: #fafafa;”>// objeto de la clase ofstream
archivo.open(#dd0000; background-color: #fafafa;”>”datos.txt”);
archivo #dd0000; background-color: #fafafa;”>”Primera línea de texto” endl;
archivo #dd0000; background-color: #fafafa;”>”Segunda línea de texto” endl;
archivo #dd0000; background-color: #fafafa;”>”Última línea de texto” endl;
archivo.close();
return 0;
}
En el programa se ha creado un objeto de la clase ofstream llamado archivo, posteriormente se utiliza la función miembro open para abrir el arcivo especificado en la cadena de texto que se encuentra dentro del paréntesis de la función. Podemos invocar a la función constructora de clase de tal manera que el archivo también se puede abrir utilizando la siguiente instrucción:
|
Al utilizar la función constructora no es necesario utilizar la función miembro open. De la misma forma que se utilizan manipuladores de salida para modificar la presentación en pantalla de los datos del programa,es posible utilizar éstos manipuladores al escribir datos en un archivo como lo demuestra el programa archiv02.cpp, observe que se utiliza un constructor para crear y abrir el archivo llamado Datos.txt:
#ff8000; background-color: #fafafa;”>#include
#include
#include
int main()
{
ofstream archivo(#dd0000; background-color: #fafafa;”>”Datos.txt”); #ff8000; background-color: #fafafa;”>// constructor de ofstream
int numero;
cout #dd0000; background-color: #fafafa;”>”Introduzca un numero:” endl;
cin >> numero;
archivo #dd0000; background-color: #fafafa;”>”El valor introducido en base 10 es: ” numero endl;
archivo resetiosflags(ios::dec);
archivo setiosflags(ios::oct);
archivo #dd0000; background-color: #fafafa;”>”en base octal es: ” numero endl;
archivo resetiosflags(ios::oct);
archivo setiosflags(ios::hex);
archivo #dd0000; background-color: #fafafa;”>”y en base hexadecimal es: ” numero endl;
archivo setiosflags(ios::uppercase|ios::showbase);
archivo #dd0000; background-color: #fafafa;”>”utilizando los manipuladores uppercase y showbase”
#dd0000; background-color: #fafafa;”>” el valor es: ” numero endl;
archivo resetiosflags(ios::uppercase|ios::showbase);
archivo resetiosflags(ios::hex);
archivo setiosflags(ios::showpos|ios::showpoint|ios::fixed);
archivo #dd0000; background-color: #fafafa;”>”Utilizando los manipuladores showpos,” #dd0000; background-color: #fafafa;”>” showpoint y fixed: ” numero endl;
archivo resetiosflags(ios::showpos|ios::showpoint|ios::fixed);
archivo #dd0000; background-color: #fafafa;”>”Finalmente el valor es ” numero endl;
archivo.close();
return 0;
}
Operaciones de lectura de archivos
Para abrir un archivo y realizar operaciones de lectura se crea un objeto de la clase ifstream y se procede prácticamente de la misma forma que lo expuesto en el apartado anterior. Después de abrir el archivo se puede leer su contenido utilizando las funciones miembro de la clase ifstream o bién el operador de extracción. Cuando se lee un archivo, por lo general se empieza al principio del mismo y se leerá su contenido hasta que se encuentre el final del archivo. Para determinar si se ha llegado al final del archivo se puede utilizar la función miembro eof como condición de un bucle while. Además se puede utilizar la función miembro fail para detectar un error al abrir el archivo, esto se demuestra en el siguiente programa, archiv03.cpp:
#ff8000; background-color: #fafafa;”>#include
int main()
{
ifstream archivo(#dd0000; background-color: #fafafa;”>”Pruebas.txt”, ios::noreplace);
char linea[128];
long contador = 0L;
if(archivo.fail())
cerr #dd0000; background-color: #fafafa;”>”Error al abrir el archivo Pruebas.txt” endl;
else
while(!archivo.eof())
{
archivo.getline(linea, sizeof(linea));
cout linea endl;
if((++contador % 24)==0)
{
cout #dd0000; background-color: #fafafa;”>”CONTINUA…”;
cin.get();
}
}
archivo.close();
return 0;
}
El programa crea un objeto de la clase ifstream para abrir el archivo llamado Pruebas.txt utilizando el constructor de clase y especificando la bandera ios::noreplace que evita que el archivo sea sobreescrito. Si por algún motivo ocurre un error al abrir el archivo se genera el mensaje de error especificado en la línea 16. En ausencia de errores el programa entra en un bucle while el cual está evaluado por efecto de la función miembro eof( ) de tal manera que el bucle se ejecuta hasta encontrar el final del archivo. Utlizando la función miembro getline( ) se obtiene una línea de texto y se exhibe en pantalla, línea 21, luego utilizamos una instrucción condicional if con el operador de módulo (%) para determinar si se han leído 24 líneas de texto. Cada vez que el contador de líneas dividido entre 24 dé como resultado un resíduo de cero el programa se detiene permitiendo leer las 24 líneas de texto previas. Para continuar se debe presionar la tecla enter y entonces el programa leerá y mostrará en pantalla las siguientes 24 líneas de texto, líneas 22 a la 26.
Referencias:
http:/
Reading and writing of files in C++
A file must be opened before you can read from it or write to it. Either the ofstream or fstreamobject may be used to open a file for writing and ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
#d6d6d6;">void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
Mode Flag | Description |
---|---|
ios::app | Append mode. All output to that file to be appended to the end. |
ios::ate | Open a file for output and move the read/write control to the end of the file. |
ios::in | Open a file for reading. |
ios::out | Open a file for writing. |
ios::trunc | If the file already exists, its contents will be truncated before opening the file. |
You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case it already exists, following will be the syntax:
#d6d6d6;">ofstream outfile; outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
#d6d6d6;">fstream afile; afile.open("file.dat", ios::out | ios::in );
When a C++ program terminates it automatically closes flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
#d6d6d6;">void close();
While doing C++ programming, you write information to a file from your program using the stream insertion operator (ofstream or fstream object instead of the cout object.
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
Following is the C++ program which opens a file in reading and writing mode. After writing information inputted by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen:
#d6d6d6;">#include#include using namespace std; int main () { char data[100]; // open a file in write mode. ofstream outfile; outfile.open("afile.dat"); cout "Writing to the file" endl; cout "Enter your name: "; cin.getline(data, 100); // write inputted data into the file. outfile data endl; cout "Enter your age: "; cin >> data; cin.ignore(); // again write inputted data into the file. outfile data endl; // close the opened file. outfile.close(); // open a file in read mode. ifstream infile; infile.open("afile.dat"); cout "Reading from the file" endl; infile >> data; // write the data at the screen. cout data endl; // again read the data from the file and display it. infile >> data; cout data endl; // close the opened file. infile.close(); return 0; }
When the above code is compiled and executed, it produces the following sample input and output:
#d6d6d6;">$./a.out Writing to the file Enter your name: Zara Enter your age: 9 Reading from the file Zara 9
Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.
Credits:
http:/
Input: Text
Es muy sencillo. Como es un texto el que queremos que el usuario introduzca, lo convertiremos a string.
Ejemplo:
Link: https:/
#Mastery28
Como leer o escribir en documentos en c++
para escribir en un documento primeramente necesitamos la realización de un archivo de texto, en el cual la base para hacerlo es la siguiente
// writing on a text file
//Reference: http:/
usingnamespacestd;
int main () {
ofstream myfile (“Write.txt”);
if(myfile.is_open()) {
myfile “This is a line.n”;
myfile “Hello world.n”;
myfile.close();
}
else{
cout “Unable to open file”;
}
return0;
}
en lo cual ahi tenemos el documento en el cual ingresaremos los datos usamos la libreria fstream, se abre el archivo y se ingresa lo que se quiere escribir en el documento
en cambio para la lectura de los documentos contamos con un procedimiento parecido, que es el siguiente:
// reading a text file
//Reference: http:/
usingnamespacestd;
intmain () {
string line;
ifstream myfile (“CNC.txt”);
if(myfile.is_open()){
while( getline (myfile,line) ){
cout ‘n’;
}
myfile.close();
}
else{
cout “Unable to open file”;
}
return0;
}
en este, tenemos que abre el archivo y este es leido linea por linea y convertida en strings,
para esto tenemos que usar la libreria fstream y string,
abril archivo con el comando ifstream y leer cada linea con el get line y este guardara cada linea.
Comments Off on Mastery 28
Posted in Blogs, Syndicated, TC1017 Blogs
Programs in Python are able to receive input coming from the user. The function able to do this is the input function. When this function is called, the program stops and waits for the user to type something. The program continues when the user press return or enter.
Example:
After input(), the Python shell received the text that I wrote and that piece of text was assigned to the variable text, so when I print the text variable I am able to read the same text that I typed.
Also, you can prompt to the user what to input, per example:
If you want to see the input in a new line, use the sequence n at the end of the prompt. Example:
Can you see the difference? In my opinion it looks nicer.
If you expect the user to type a certain type, you can indicate that in your code. Example:
But if I type something different than an integer I get an error message:
So, this is basically how you handle basic input from the user.
#Mastery28
Comments Off on User Input (text based) in Python (basic). Mastery 28.
Posted in Blogs, Syndicated, TC1014 Blogs
Tagged #45, #mastery28, Mastery
Comments Off on #Mastery28
Posted in Blogs, Syndicated, TC1014 Blogs
Tagged #mastery28, #TC1014, ken'sCourse, masteries
Comments Off on #Mastery28
Posted in Blogs, Syndicated, TC1014 Blogs
Tagged #mastery28, #TC1014, ken'sCourse, masteries
Comments Off on #Mastery28
Posted in Blogs, Syndicated, TC1014 Blogs
Tagged #mastery28, #TC1014, ken'sCourse, masteries
Usar streams facilita mucho el acceso a ficheros en disco, veremos que una vez que creemos un stream para un fichero, podremos trabajar con él igual que lo hacemos con cin o cout.
Mediante las clases ofstream, ifstream y fstream tendremos acceso a todas las funciones de las clases base de las que se derivan estas: ios, istream, ostream,fstreambase, y como también contienen un objeto filebuf, podremos acceder a las funciones de filebuf y streambuf.
Acontinuacion hay un ejemplr de la clase ifstream:
Link to GitHub: https:/
Comments Off on Mastery 28
Posted in Blogs, Syndicated, TC1017 Blogs
Tagged #12100d, #mastery28, #TC1017