The problem you have is associated with handling the streams
of the standard library of c++
.
When you want to take the value for intr
instead of taking "Dani Martin" it takes "Dani", then you want to put a value type string
in a type int
, although it does not give an execution error, no you get the value you want (neither in intr
, nor in seg
).
You could solve the issue using getline , but you have blank lines that you want to ignore and getline
as opposed to >>
does not ignore them.
An example of a solution is the following, it is very improvable, but it is a beginning.
tema.h
#ifndef TEMA_H
#define TEMA_H
#include <string>
#include <fstream>
typedef struct{
std::string title;
std::string intr;
int seg;
}tTema;
bool cargar(tTema &tema);
void mostrar(tTema tema);
#endif
tema.cpp
#include "tema.h"
#include <iostream>
#include <sstream>
int main(){
tTema tema;
cargar(tema);
}
bool cargar(tTema &tema){
int num;
bool ok = true;
std::ifstream archivo;
archivo.open("tema.txt");
//Variable auxiliar para saber linea con informacion es
int datosLeidos= 0;
//Variable auxliar para leer las lineas del archivo
std::string linea;
while (std::getline(archivo, linea)) {
//Si la linea esta vacia, continua con la proxima
if (linea.empty()) continue;
std::stringstream is(linea);
//Dependiendo de la linea leida
//es la variable a la cual se asocia el valor
switch(datosLeidos) {
case 0:
is >> num;
break;
case 1:
is >> tema.title;
break;
case 2:
//Necesitas tomar toda la linea
getline(is, tema.intr);
break;
case 3:
is >> tema.seg;
break;
default:
std::cout << "Ya se leyeron 4 lineas. No hace nada.";
}
datosLeidos++;
}
//Si cargo los datos entonces esta ok.
ok= (4 >= datosLeidos);
//Para ver que hizo lo esperado
std::cout << num << std::endl;
std::cout << tema.title << std::endl;
std::cout << tema.intr << std::endl;
std::cout << tema.seg << std::endl;
return ok;
}
If you are going to keep doing things in C++
with input / output, I suggest you look at the Boost libraries on the subject ( Boost I / O ).
References (in English):
SO: Reading string with spaces in c ++
stringstream on cplusplus.com