2014-10-05 3 views
-2

Я пытаюсь прочитать данные из TXT-файла и поместить его содержимое в связанный список, который содержит две строки на узел. Поскольку некоторые из строк в файле .txt содержат пробелы, и я бы предпочел оставить их как есть, чем убить пробелы, я использую std :: getline().std :: getline "blends" strings вместе

У меня есть файл .txt, отформатированный как это:

"Туризм, отдых & Спортивный менеджмент"

«TRS»

"Антропология"

«ANT»

И так далее, но без пустых линий между каждой строкой. Связанный список имеет метод print(), который печатает данные в этом формате: data1/data2; data1/data2:

Так что, когда я печатаю узел с data1 == "Туризм, отдых & Спорт Менеджмент" и data2 == "TRS" желаемый результат:

«Туризм, отдых & Sports Management "/" TRS ";

ОДНАКО, что я на самом деле получаю:

«ТРС» изм, отдых & Sports Management»

Однако, когда я прочитал строки и присвоить их строки, а затем распечатать эти строки без вставляя их в связный список, я получаю правильный вывод, что это

std::cout << data1 << std::endl; 
std::cout << data2 << std::endl; 

правильно выход:.

"Туризм, отдых & Управление спортом"
"TRS"

Что дает?

Edit: заголовок Связанный список:

#ifndef _2DLL_H_ 
#define _2DLL_H_ 
#include <iostream> 
#include <string> 



class Llist{ 
    struct node{ 
    //node member var 
    std::string department; 
    std::string abv; 
    node * next; 

    //node member methods 

    std::string search(std::string dep); 
    void print(); 
    void remove(const std::string dep); 
    void clear(); 
    //constructer 
    node(const std::string dep , const std::string a):department(dep), abv(a), next(NULL){} 

    };// end node 

public: 
    //Llist member var 
    node * head; 

    //LList constructer & destructor 
Llist():head(NULL){} 
    ~Llist(){clear();} 

    //Llist member functions 
    std::string search(const std::string dep); 
    void insert(const std::string dep , const std::string a); 
    void print(); 
    void remove(const std::string dep); 
    void clear(); 
    const int operator[](unsigned int index)const; 
};// end Llist 


#endif //_2DLL_H_ 

Связанный список .cpp

#include "2DLL.h" 
#include <algorithm> 


//=========INSERT============== 

void Llist::insert(const std::string dep, const std::string a){ //will just prepend. Fuck the police; 
    node * n = new node(dep , a); 
    n->next = head; 
    head = n; 
} 

//========PRINT================= 
void Llist::print(){ 
    if(head==NULL){ 
    std::cout << "ERROR: List is empty" << std::endl; 
    } 
    else{ 
    head->print(); 
    } 
} 

void Llist::node::print(){ 
    if(next==NULL){ 
    std::cout << department << ";" << abv << std::endl; 
    } 
    else{ 
    std::cout << department << ";" << abv << "/" ; 
    std::cout << std::endl; 
    next->print(); 
    } 
} 

//=======REMOVE======== 

void Llist::remove(const std::string dep){ 
    if(head==NULL){ 
    std::cout << "ERROR: List is empty" << std::endl; 
    } 
    else{ 
    head->remove(dep); 
    } 
} 

void Llist::node::remove(const std::string dep){ 
    if(next->department == dep){ 
    node * n = next; 
    next = n->next; 
    delete n; 
    } 
    else{ 
    next->remove(dep); 
    } 
} 

//===========CLEAR()================== 

void Llist::clear(){ 
    if(head==NULL){ 
    std::cout << "ERROR:List is empty" << std::endl; 
    } 
    else{ 
    head->clear(); 
    head = NULL; 
    } 
} 

void Llist::node::clear(){ 
    if(this==NULL){ 
    return;  

    } 
    else{ 
    next->clear(); 
    delete this; 
    } 

} 

//=========OPERATOR============= 
/* 
const int Llist:: operator[] (unsigned int index) const{ 
    node * n = head; 
    for(int i = 0 ; i < index && n!=NULL ; ++i){ 
    n=n->next; 
    } 
    return n->data; 
} 

*/ 

//========SEARCH==================== 

std::string Llist::search(std::string dep){ 
    if(head == NULL){ 
    std::cout << "ERROR: List is empty" << std::endl; 
    return "ERROR"; 
    } 
    else{ 
    //dep.erase(std::remove(dep.begin(),dep.end(),' '),dep.end()); 
    //std::cout << dep << std::endl; 
    return head->search(dep); 
    } 
} 

std::string Llist::node::search(std::string dep){ 
    if(department == dep){ 
     return abv; 
    } 
    else{ 
     return next->search(dep); 
    } 
    } 

Осуществление Чтение

#include "genCollege.cpp" 
#include "genDepartment.cpp" 
#include "2DLL.cpp" 
#include <ctime> 
#include <fstream> 

using namespace std; 


int main(){ 
    std:: ifstream file; 
    file.open("DepList.txt"); 
    std::string department; 
    std::string abv; 

    srand(time(0)); 
    /*for (int i = 0 ; i < 30 ; i++){ 
     std::string college = genCollege(); 
     std::string department = genDepartment(college); 

     std::cout << "College: "<< college << std::endl; 
     std::cout << "\t" << "Department: " << department << std::endl; 
     std::cout << std::endl; 
    } */ 
    Llist list; 

    while(file.is_open()){ 
     if(file.eof()){break;}; 

     std::getline(file , department); 
     std::getline(file, abv); 

     list.insert(department , abv); 

    } 
    //file.close(); 
    list.print(); 



    return 0 ; 
} 
+1

5-страничное эссе (плохо отформатированное) и без кода? Что дает? –

+0

Похоже, что ваши узлы не правильно выделяют независимое хранилище для каждой строки. У узла есть 'std :: string'? 'Символ []'? 'char *'? –

+0

Я понял, что это может быть просто причуда с использованием метода getline() в целом и о котором я не знал. Какой код вы хотели бы видеть? Вам нужно только спросить :) –

ответ

0

Как пользователь нм предположил, что, казалось, что из-за Я читал текстовый файл для Windows и запускал программу на Ubuntu, outp Ут выглядел не так. Его ответ слово в слово:

«У вас есть текстовый файл, созданный для Windows с \r\n в качестве терминатора линии. Ваша программа либо работает на un * x, либо не открывается файл в текстовом режиме. \r в конце каждой строки, которая портит окна терминала. "

Он предложил мне проверить, если последний символ в строке после того, как я использовал std::getline() это \r и, если это так, чтобы удалить его из строки.Я сделал это, просто сделав подстроку строк, о которых идет речь, после того как я их приобрел с помощью std::getline()

Затем я вставил новые подстроки в связанный список, и теперь метод print() выдает по желанию.