gazela 0 Posted March 24, 2011 Report Share Posted March 24, 2011 Boas pessoal, precisava aqui de uma ajudinha. Tenho o seguinte ficheiro de texto: Uploaded with ImageShack.us E tenho o seguinte código para mostrar o que está guardado no ficheiro: int main() { ifstream inBooksFile ( "books.txt"); if (!inBooksFile ) { cerr << "file not found" << endl; exit (1); } string ID; unsigned int intID; string title; string author; string quantity; unsigned int intQuantity; if (inBooksFile.is_open()) { while (inBooksFile.good()) { getline (inBooksFile, ID); getline (inBooksFile, title); getline (inBooksFile, author); getline (inBooksFile, quantity); intID = string_to_int(ID); intQuantity = string_to_int(quantity); cout << "ID: " << intID << endl; cout << "title: " << title << endl; cout << "author: " << author << endl; cout << "quantidade: " << intQuantity << endl; } inBooksFile.close(); } else cout << "Unable to open file"; return 0; } unsigned int string_to_int (string dados) { unsigned int intReturn; intReturn = atoi (dados.c_str() ); return (intReturn); } O código parece estar a funcionar bem, mas imprime o último livro repetido e não estou a perceber porque. Estou a converter o ID e a quantidade para inteiro porque vou precisar de usar estes números depois como inteiros e não como strings. Uploaded with ImageShack.us Se alguém me puder ajudar nisto =S Link to post Share on other sites
KTachyon 276 Posted March 24, 2011 Report Share Posted March 24, 2011 Observa: O livro vem repetido, mas o ID vem diferente. Será que tem alguma coisa a haver com o ficheiro ainda não ter acabado ... (tempo para pensar) ... Ou seja, o ficheiro acaba quando vais buscar a linha do ID e depois não consegue ir buscar o resto das linhas, pelo que imprime o que se encontra nas variáveis nesse momento (o livro repetido). “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare Link to post Share on other sites
gazela 0 Posted March 26, 2011 Author Report Share Posted March 26, 2011 Não tinha reparado no ID diferente Com o código que tinha para guardar as informações estava a meter uma linha em branco no fim :wallbash: obrigado Link to post Share on other sites
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now