Строки и способы получения ввода в C ++ - PullRequest
0 голосов
/ 25 февраля 2019

В настоящее время я работаю над тем, что берет входной файл пользователя и составляет связанный список указателей объектов (4 отдельных файла).Работая над функцией lookup, которая просматривает связанный список, чтобы увидеть, находится ли переданный заголовок внутри связанного списка, я заметил, что все мои сохраненные заголовки на 1 символ длиннее, чем они должны быть. Например, в моем случае поиска «Spaces VS Tabs» (18) я иду и вызываю tempPtr-> getTitle () в моей функции поиска в vlist.cpp, а затем получаю длину этого.Он возвращает длину 19 , и я действительно запутался в этом.Чтобы было ясно, это заголовки, которые хранятся в объектах, которые имеют ненормальную длину;вы можете посмотреть в main.cpp, как я их получил.

До сих пор я использовал странное количество cin.ignore () для получения ввода, так что я чувствую, что это может быть так.Кроме этого, я понятия не имею, как дополнительный символ добавляется в мои названия.

main.cpp

#include <iostream>
using namespace std;
#include "vlist.h"
#include "video.h"

int main()
{
    string firstLine, secondLine, thirdLine, userPreference;
    float fourthLine;
    int fifthLine;
    VList list;

    string lookUp = "Spaces Versus Tabs";

    cin >> userPreference; //Why do I need two cin.ignore()'s after this? WHO KNOWS?!
    cin.ignore();
    cin.ignore(); 

    while(cin.peek() != EOF) {
        getline(cin, firstLine);
        getline(cin, secondLine);
        getline(cin, thirdLine);
        cin >> fourthLine;
        cin >> fifthLine;
        cin.ignore();
        cin.ignore();
        Video * tempVid = new Video (firstLine, secondLine, thirdLine, fourthLine, fifthLine); // Assign object
        list.insert(tempVid);
    }
    list.lookup(lookUp);
    return 0;
}

vlist.cpp

#include <iostream>
using namespace std;
#include "vlist.h"

VList::VList() {
    m_head = NULL;
}

VList::~VList() {
    Node *ptr = m_head;
    while (ptr != NULL) {
        Node *temp;

        temp = ptr;
        ptr = ptr->m_next;
        delete temp;
    }
}

void VList::insert(Video *myVid) {
    m_head = new Node(myVid, m_head);

    int occurance = 0;
    Node *ptr = m_head;
    Node *staticPtr = m_head;
    Video *tryingToAdd = staticPtr->m_vid;

    while (ptr != NULL) {
        Video *tempPtr = ptr->m_vid;
        //Look for title, if you find it, occurance ++
        cout << tryingToAdd->getTitle() << endl;//This only works if I have << endl; at the tail of it. Why?
        if(occurance > 1) {
            cout << "Couldn't insert video <" << tempPtr->getTitle() << ">, already in list.";
            return;
        }
        ptr = ptr->m_next;
    }

}

void VList::length() {
    //ADD IN A CHECK FOR EMPTY LIST HERE
    int lengthCounter = 0;
    Node *ptr = m_head; 
    while (ptr != NULL) {
        lengthCounter++;
        ptr = ptr->m_next;
    }
    cout << lengthCounter << endl;
}

void VList::lookup(string title) {
    bool isInList = false;//Saftey check
    Node *ptr = m_head; 
    while (ptr != NULL) {
        Video *tempPtr = ptr->m_vid;
        string compareMe = tempPtr->getTitle();
        cout << compareMe.length() << " - " << compareMe << endl;
        if(title.compare(compareMe) == 0) {
            tempPtr->print();
        }
        ptr = ptr->m_next;
    }
    if(!isInList) {
        cout << "Title <" << title << "> not in list." << endl;
        cout << title.length() << endl;
    }
}

void VList::remove(string title) {
    bool isInList = false;//Saftey check
    Node *ptr = m_head; 
    while (ptr != NULL) {
        Video *tempPtr = ptr->m_vid;
        string compareMe = tempPtr->getTitle();
        if(title.compare(compareMe) == 0) {
            //REMOVE CURRENT VIDEO
        }
        ptr = ptr->m_next;
    }
    if(!isInList) {
        cout << "Title <" << title << "> not in list, could not delete." << endl;
    }
}

void VList::print() {
    Node *ptr = m_head; 
    while (ptr != NULL) {
        Video *tempPtr = ptr->m_vid;
        tempPtr->print();//Prints ALL information for a single video
        ptr = ptr->m_next;
    }
}

vlist.h

#ifndef VLIST_H
#define VLIST_H
#include "video.h"

class VList
{
    public:
        VList();
        ~VList();
        void insert(Video *myVid);
        void print();
        void length();
        void lookup(string title);
        void remove(string title);
    private:
        class Node
        {
            public:
                Node(Video *myVid, Node *next) {    
                    m_vid = myVid; 
                    m_next = next;
                }
                Video *m_vid;
                Node *m_next;
        };
        Node *m_head;   
};

#endif

video.cpp

#include "video.h"
#include <iostream>

using namespace std;

Video::Video(string title, string URL, string comment, float length, int rating) {
    vidTitle = title;
    vidURL = URL;
    vidComment = comment;
    vidLength = length;
    vidRating = rating;
}

void Video::print() { //Print entire video object information
    cout << getTitle() << endl;
    cout << getURL() << endl;
    cout << getComment() << endl;
    cout << getLength() << endl;
    cout << getRating() << endl;
    return;
}

video.h

#ifndef VIDEO_H
#define VIDEO_H

#include <string>
#include <iostream>

using namespace std;

class Video
{
    public:
        Video(string title, string URL, string comment, float length, int rating);
        int getRating() {
            return vidRating;
        }
        float getLength() {
            return vidLength;
        }
        string getTitle() {
            return vidTitle;
        }
        string getURL() {
            return vidURL;
        }
        string getComment() {
            return vidComment;
        }
        void print();
    private:
        string vidTitle, vidURL, vidComment, vidPreference;
        float vidLength;
        int vidRating;
};

#endif
...