Mostrando Codigo - C & C++
ifstream - Leer archivo de texto .txt
Con el uso de ifstream mostramos este ejemplo para leer un archivo de texto aunque puede utilizarse para otro tipo de archivos
EXPLICACION
Incluir las cabeceras necesarias
#include <iostream> #include <iomanip> #include <fstream> using namespace std;
Declarar la variable
ifstream archivo;
Abrimos el archivo
archivo.open("C:\archivodatos.txt");
Comprobamos que el archivo esta abierto y puede ser leido
if (!archivo) {
cerr << "No pudo leerse el archivo";
exit(1); // parar
}
Una vez comprobado leemos el archivo
while (archivo >> x) {
sum = sum + x;
}
Cerramos el archivo y liberamos recursos del sistema
archivo.close();
Mostramos el resultado
cout << "Resultado = " << sum << endl;
return 0;
CODIGO
// Codigo ofrecido por Tutores.org
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
int sum = 0;
int x;
ifstream archivo;
if (!archivo) {
cerr << "No pudo leerse el archivo";
exit(1); // parar
}
while (archivo >> x) {
sum = sum + x;
}
archivo.close();
cout << "Resultado = " << sum << endl;
return 0;
}
ENLACE AL CODIGO
Si quieres enlazar desde tu pagina a este codigo<!-- Inicio enlace Tutores.org -->
<a title="Tutores.org - ifstream - Leer archivo de texto .txt" href="http://www.tutores.org/codigo/1864/" target="_blank">ifstream - Leer archivo de texto .txt</a>
<!-- Final enlace Tutores.org -->
<a title="Tutores.org - ifstream - Leer archivo de texto .txt" href="http://www.tutores.org/codigo/1864/" target="_blank">ifstream - Leer archivo de texto .txt</a>
<!-- Final enlace Tutores.org -->
COMENTARIOS











