Tag Archives: #mastery28

User input (text based) in Python (basic)

AQUI LES DEJO EL LINK DEL VIDEO DONDE EXPLICO

https://www.dropbox.com/s/3i42s40vuyjyohc/Input%20Mastery%2028.avi?dl=0

 

28

1014

#Mastery 28 – Reading and writing of files in C++

Manejo de archivos en c++

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:

int main()
{
    
ofstream archivo;  

    archivo.open();

    archivo endl;
    
archivo endl;
    
archivo 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:

int main()
{
    
ofstream archivo();  int numero;
    
    
cout endl;
    
cin >> numero;
    
archivo numero endl;
    
    
archivo resetiosflags(ios::dec);
    
archivo setiosflags(ios::oct);
    
archivo numero endl;
    
    
archivo resetiosflags(ios::oct);
    
archivo setiosflags(ios::hex);
    
archivo numero endl;
    
archivo setiosflags(ios::uppercase|ios::showbase);
    
archivo 
numero endl;
    
    
archivo resetiosflags(ios::uppercase|ios::showbase);
    
archivo resetiosflags(ios::hex);
    
archivo setiosflags(ios::showpos|ios::showpoint|ios::fixed);
    
archivo numero endl;
    
    
archivo resetiosflags(ios::showpos|ios::showpoint|ios::fixed);
    
archivo 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:

int main()
{
    
ifstream archivo(ios::noreplace);
    
char linea[128];
    
long contador 0L;

    if(archivo.fail())
    
cerr endl;
    else
    while(!
archivo.eof())
    {
        
archivo.getline(lineasizeof(linea));
        
cout linea endl;
        if((++
contador 24)==0)
        {
            
cout ;
            
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://www.programacionenc.net/index.php?option=com_content&view=article&id=69:manejo-de-archivos-en-c&catid=37:programacion-cc&Itemid=55

1017 28

Mastery 28

Reading and writing of files in C++

Opening a File:

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.

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:

Similar way, you can open a file for reading and writing purpose as follows:

Closing a File

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.

Writing to a File:

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.

Reading from a File:

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.

Read & Write Example:

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:

When the above code is compiled and executed, it produces the following sample input and output:

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://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm

1017 28

Mastery28

Input: Text

Es muy sencillo. Como es un texto el que queremos que el usuario introduzca, lo convertiremos a string.

Ejemplo:

Link: https://github.com/LizethAcosta/Tareas/blob/master/Mastery28

28

Mastery 28

28 1017

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://www.cplusplus.com/doc/tutorial/files/

 

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://www.cplusplus.com/doc/tutorial/files/

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.

User Input (text based) in Python (basic). Mastery 28.

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.

28

 

 

 

 

 

#Mastery28

#Mastery28

#Mastery28

Mastery 28

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 ofstreamifstream y fstream tendremos acceso a todas las funciones de las clases base de las que se derivan estas: iosistreamostream,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://github.com/JoseSanchez12/Quizz11/blob/master/q1.cpp