std::getline "blends" strings together - c++

I am attempting to read data from a .txt file and put its contents into a linked list that holds two strings per node. Because some of the strings in the .txt file contain spaces, and I'd rather leave them as is than kill the spaces, I am using std::getline().
I have the .txt file formatted as so:
"Tourism, Recreation & Sports Management"
“TRS”
"Anthropology"
“ANT”
And so on but without the blank lines between each line. The linked list has a print() method that prints the data in this format : data1 / data2 ; data1 / data2:
So, when I print a node with data1 == "Tourism, Recreation & Sports Management" and data2 == "TRS" the desired output is:
"Tourism, Recreation & Sports Management" / "TRS";
HOWEVER, what I actually get is:
"TRS"ism, Recreation & Sports Management"
However, when I read the lines and assign them to strings, and then print out those strings without inserting them into the linked list, I get correct output. That is
std::cout << data1 << std::endl;
std::cout << data2 << std::endl;
Will correctly output:
"Tourism, Recreation & Sports Management"
"TRS"
What gives?
Edit:
Linked List header:
#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_
Linked List .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);
}
}
Implementation of the Reading
#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 ;
}

As the user n.m suggested, it seemed that because I was reading a text file for Windows and running program on Ubuntu, the output looked wrong. His answer word for word:
"You have a text file created for Windows that has \r\n as the line terminator. Your program either runs on a un*x or fails to open the file in text mode. Thus you are getting \r at the end of each string, which messes your terminal window. "
He suggested I check to see if the the last character in the string after I've used std::getline() is \r and, if it is, to remove it from the string. I did this by simply making a substring of the strings in question after I acquired them with std::getline()
I then inserted the new substrings into the linked list and the print() method now outputs as desired.

Related

How do I make my for loop go to the end of the char* array and put every city in a linked list(The citys are divided by a whitespace)

So in my homework I need to sort cities alphabetically by the first letter, if there are more citys with the same starting letter, then output them in the reverse order.
I have managed to get the the input from a file into the buffer char array.
But when I try to to sort it(go through the array it doesnt work)
#include <iostream>
#include <fstream>
using namespace std;
class List
{
struct Node
{
char* input;
Node* next;
};
Node* head;
Node* tail;
public:
List()
{
head = NULL;
tail = NULL;
}
void createnode(char* city)
{
Node* temp = new Node;
temp->input= city;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
Node* point = new Node;
point->input= city;
point->next = head;
head = point;
}
}
void display()
{
Node* point = head;
if (point == NULL)
{
cout << endl << "====================================" << endl << "List Doesnt exist/is deleted" << endl << "====================================" << endl;
return;
}
cout << endl << "your list:" << endl;
while (point != NULL)
{
cout << point->input<< "\t";
point = point->next;
}
cout << endl;
}
};
int main()
{
////////////////THE PART WHERE I EXTRACT INFORMATION FROM THE INPUT FILE
ifstream file("paldies.in", ifstream::binary);
fstream file2;
file2.open("paldies.out", ios::out);
if (!file)
{
cout << "Error desune!";
return 0;
}
file.seekg(0, file.end);
int length = file.tellg();
file.seekg(0, file.beg);
char * buffer = new char[length];
cout << "Reading " << length << " characters....." << endl;
file.read(buffer, length);
if (length == 0)
{
char nothing[8] = "Nothing";
file2.write(reinterpret_cast<char*>(nothing), 8 * sizeof(char));
file.close();
file2.close();
return 0;
}
if (file)
{
cout << "all characters read succesfully.";
}
else
{
cout << "error: only " << file.gcount() << " could be read";
}
file.close();
////////////////////////////THIS IS THE PART THATS NOT WORKING FOR ME
List a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
for (buffer; *buffer != '\0'; buffer++)
{
if (buffer[0] == 's')
{
char s_begining[255] = "";
for (int i = 0; buffer[0] != ' '; i++)
{
s_begining[i] = buffer[0];
buffer++;
}
s.createnode(s_benining);
}
buffer++;
}
cout << endl<<buffer<<endl;
s.display();
file2.close();
return 0;
}
Input: springfield philadelphia detroit cleveland miami denver springfield seattle jacksonville
Correct output: cleveland denver detroit jacksonville miami philadelphia seattle springfield springfield
Actual output: since im just testing with the letter s it comes out as springfield only once, if I change the char s_begining declaration to outside of the if statement or the loop it gives different results.
I have a feeling that the problem is somewhere in the first for loop because when I take it out the first element goes into the list just fine, but when I put back in sometimes theres an exception, nothing happens(Empty list), or the list has 4 inputs with also garbage data in them.
Also if I delete the buffer++; at the end of the first for loop it also breaks stuff.
So far I have gotten 1 city name in the list correctly and thats the first one (springfield).
EDIT: I forgot to mention that I am only allowed to use the fstream library, everything elese has to be coded by myself!
A lot of what you’re trying to do can be achieved using the STL:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main() {
// 0. Set up variables
std::ifstream inFile("pladies.in");
std::ofstream outFile("pladies.out");
std::vector<std::string> cities;
// 1. Read each line of the input file to a vector
std::string line;
while (std::getline(inFile, line)) {
cities.push_back(line);
}
// 2. Sort the vector alphabetically
std::sort(cities.begin(), cities.end());
// 3. Write the vector to the output file
std::copy(cities.begin(), cities.end(), std::ostream_iterator<std::string>(outFile, "\n"));
}
(repl.it)

How do you initialize template class members that uses other template classes?

I'm having trouble correctly setting up and accessing my member functions of a class. This node class is being used to build a Max Heap Tree. However, when the tree is being initialized, I'm getting garbage data and not what I am initializing it to.
#ifndef HEAPNODE_H_INCLUDED
#define HEAPNODE_H_INCLUDED
#include <iostream>
#include <cstdlib>
#include <array>
using namespace std;
template <class Type> class HeapNode {
private:
int key;
Type value;
public:
HeapNode(int key, Type const &value) {
this->key = key;
this->value = value;
}
// Returns the key of the node
int getKey() {
return key;
}
// Returns the value of the node
Type getValue() {
return value;
}
// Displays the node
void displayNode() {
cout << "Key: " << key << "\tValue: " << value << endl;
}
};
#endif
Here is the class that builds my Heap Tree. I've tried setting the initializations in the constructor every which way, and I'm still getting junk data. In addition, I set the constructor to take an integer, but when I'm creating a tree in my driver program, it won't let me put an argument for it which initiates an array of that size.
#ifndef MAXHEAPTREE_H_tINCLUDED
#define MAXHEAPTREE_H_INCLUDED
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "HeapNode.h"
using namespace std;
template <class Type> class MaxHeapTree {
private:
HeapNode<Type> *array;
HeapNode<Type> *root;
int elementSize;
int height;
int leafCounter;
public:
// Constructor
MaxHeapTree(int n = 10) : elementSize(0), height(0), leafCounter(0) {
this->elementSize = elementSize;
this->height = height;
this->leafCounter = leafCounter;
HeapNode<Type> *array = new HeapNode<Type>[n];
}
// Destructor
~MaxHeapTree();
void arrayDisplay() {
cout << "Original array size: " << sizeof(array)/4 << endl;
}
// Returns the number of elements in the tree
int getSize() {
return elementSize;
}
// Returns the height of the tree
int getHeight() {
return height;
}
// Returns the number of leaves in the tree
int leaves() {
return leafCounter;
}
int countLines(const string fileName) {
string line;
int lineCount = 0;
ifstream myFile (fileName.c_str());
if (myFile.is_open()) {
while (getline(myFile, line)) {
lineCount++;
}
}
else {
cout << "Error opening file" << endl;
}
myFile.close();
return lineCount;
}
// Reads structure from a text file and builds a max heap
void buildTree(const string fileName) {
string line;
string key;
string value;
int lines = countLines(fileName);
int i = 0;
cout << "Lines: " << lines << endl;
HeapNode<Type> *newArray[lines];
cout << "Size of newArray: " << sizeof(newArray)/4 << endl;
ifstream myFile (fileName.c_str());
if (myFile.is_open()) {
while (getline(myFile, line)) {
key = line.substr(0, 1);
int x = atoi(key.c_str());
value = line.substr(1);
HeapNode<Type> *hNode = new HeapNode<Type>(x, value);
newArray[i] = hNode;
cout << "newArray[" << i << "] = ";
newArray[i]->displayNode();
i++;
}
}
else {
cout << "2 - Error opening file." << endl;
}
myFile.close();
}
};
#endif
How do you initialize template class members that uses other template classes?
In the same way you initialize members of non templates that don't use other templates.
when the tree is being initialized, I'm getting garbage data and not what I am initializing it to.
I was using MaxHeap<string> *heapTree1;
Well, there's your problem. Apparently you never created an instance of MaxHeap<string>.

Link List - no operator '<<' matches

My c++ is really poor. Anyhow with the code snippet bellow why do I get a error on the << in the do while loop when outside of it I get no error. The error is: no operator "<<" matches these operands. However the string w picks up the word fine. I read somewhere I may have to overload it but why? And how would I over load it for a link list.
Thanks in advance.
void print()
{
HashTable *marker = headOne;
HashTable *inList;
for( int i = 0; i < tableSize; i++ )
{
cout << i << ": " << marker->number << endl;
if(marker->child != NULL)
{
inList = marker;
do
{
string w = inList->word;
cout << w << endl;
inList = inList->child;
}
while(inList != NULL);
}
marker = marker->next;
}//end for loop
}
In order to be able to cout a std::string you have to include:
#include <string>
#include <iostream>
This works:
// Missing includes and using
#include <string>
#include <iostream>
using namespace std;
// missing struct
struct HashTable {
HashTable* next;
HashTable* child;
string word;
int number;
};
// missing vars
HashTable ht;
HashTable* headOne = &ht;
int tableSize = 5;
// Unchanged
void print()
{
HashTable *marker = headOne;
HashTable *inList;
for( int i = 0; i < tableSize; i++ )
{
cout << i << ": " << marker -> number << endl;
if(marker->child != NULL)
{
inList = marker;
do
{
string w = inList -> word;
cout << w << endl;
inList = inList -> child;
}
while(inList != NULL);
}
marker = marker -> next;
}//end for loop
}
I read somewhere I may have to overload it but why?
Because there's no overload that matches your need.
And how would I over load it for a link list.
You can do this outside of your class or struct:
(where T is the type of the object that you want to print)
std::ostream& operator<<(std::ostream& os, const T& obj)
{
/* write obj to stream */
return os;
}
This is just an example that prints a vector:
std::ostream& operator<<(std::ostream& os, vector<int>& obj)
{
for (auto &i : obj)
os << i << " ";
return os;
}
Then I would be able to simply do this cout << n.vec; where n is the class object and vec the name of a vector of ints.

Stuck on a linked list multiple class implementation

I have been working on this project for several days. This project contains 3 classes. The first is a DNA class that stores a DNA object. The second is a database class that reads a file and parses commands and data and deals with it accordingly. The last is a DNA list class that is a linked list of nodes that have pointers to DNA objects.
I've completed my linked list building method. It is required to be a push_back method that adds nodes at the end of the list. My problem arises when I try to search the list for a certain node. This has to be a method that returns a DNA* if a DNA object with id exists in the list; otherwise it returns NULL.
My plan is to use this method to print and also delete the node. I can't seem to get this method to work. Obviously I'm a little shaky with pointers. It took me several hours to implement my push_back method. Here is my code. Any guidance or help is appreciated.
DNA.h
#ifndef DNA_H
#define DNA_H
#include <string>
class DNA{
public:
// overloaded constructor for DNA class
DNA(std::string, int, std::string, int, int);
// print function
void print();
int getID();
private:
std::string m_label; // variable to hold label
int m_id; // variable to hold id
std::string m_sequence; // variable to hold sequence
int m_length; // variable to hold length
int m_index; // variable to hold index
};
#endif
DNA implementation
#include "DNA.h"
#include <iostream>
#include <string>
using namespace std;
DNA::DNA(string label, int id, string sequence, int length, int index){
m_label = label;
m_id = id;
m_sequence = sequence;
m_length = length;
m_index = index;
}
void DNA::print(){
cout << "DNA:" << '\t' << "label: " << m_label << '\t' << "ID: " << m_id << '\t' << "Sequence: " << m_sequence << endl << "Length: " << m_length << '\t' << "cDNAStartIndex: " << m_index << endl << endl;
}
int DNA::getID(){
return m_id;
}
Database class
#ifndef SEQUENCEDATABASE_H
#define SEQUENCEDATABASE_H
#include <string>
#include <fstream>
#include "DNA.h"
#include "DNAList.h"
class SequenceDatabase {
public:
SequenceDatabase();
// function to import the data file, parse the data, and perform the required output
void importEntries(std::string);
private:
DNAList list;
};
#endif
Database implemenation
#include "SequenceDatabase.h"
#include "DNA.h"
#include "DNAList.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
SequenceDatabase::SequenceDatabase(){
DNAList list;
}
// function reads in the filename creates a data stream and performs the requested actions
void SequenceDatabase::importEntries(string inputFile){
ifstream dnaFile(inputFile);
char command;
string label, sequence;
int id, length, index;
while(dnaFile >> command){
DNA* p;
if(command == 'D'){
dnaFile >> label >> id >> sequence >> length >> index;
DNA data(label, id, sequence, length, index);
p = new DNA(label, id, sequence, length, index);
list.push_back(p);
}
if(command == 'P'){
dnaFile >> id;
cout << "Printing " << id << " ..." << endl << endl;
p = list.findId(id);
if(p == nullptr)
cout << "Can not find item " << "(" << id << ")!" << endl << endl;
else
p-> print();
}
}
dnaFile.close();
}
Finally my list class
#ifndef DNALIST_H
#define DNALIST_H
#include "DNA.h"
#include "sequenceDatabase.h"
struct DNANode{
DNA* data;
DNANode* next;
DNANode* prev;
};
class DNAList{
public:
DNAList();
DNAList(DNA* newDNA);
void push_back(DNA* newDNA);
DNA* findId(int);
void obliterate(int id);
int size();
private:
DNANode* head;
int list_size;
};
#endif
List implementation
#include "DNA.h"
#include "sequenceDatabase.h"
#include "DNAList.h"
#include <iostream>
using namespace std;
DNAList::DNAList(){
head = new DNANode;
head->next = nullptr;
list_size = 0;
}
DNA* DNAList::findId(int id){ // this function is my problem
DNANode* current;
current = head;
while(current->next != nullptr){
if(current->data->getID() == id){
return current->data;
}
current = current->next;
}
return nullptr;
}
int DNAList::size(){
return list_size;
}
void DNAList::push_back(DNA* newDNA){
DNANode* current;
DNANode* last;
DNANode* p;
p = new DNANode;
p->data = newDNA;
last = nullptr;
current = head;
cout << "Adding " << newDNA->getID() << " ..." << endl << endl;
while(current != nullptr){
last = current;
current = current->next;
}
if(current == head->next){
p->next = nullptr;
p->prev = head;
head->next = p;
}
else{
p->next = current;
p->prev = last;
last->next = p;
}
list_size++;
}
I wasn't sure if I should post the whole code, but i felt it was needed to understand the problem. My problem arises when i try to call the find function to print the data in the node.
Your head member variable of DNAList is initialized with new DNANode. Since DNANode doesn't have an explicit constructor, its compiler generated one will not initialize the pointers data, next and prev. next is initialized on the next line, but data is left as a garbage value.
Inside findId, this line is executed:
if (current->data->getID() == id){
However the first time around the loop, current is pointing head. This means you are trying to look at the garbage value, which will possibly crash.
One solution is to change the findId function to start at head->next, another is to initialise the data pointer in head to nullptr and check that data is not nullptr before you access it.
A better solution might be to just have head as nullptr to start with, rather than having a dummy DNANode at the top. This would involve changing some of the code in push_back, but might make it easier to understand.
Aha. I think what is causing the problem is that towards the end of your SequenceDatabase::importEntries() method you are setting if(p=nullptr) instead of making the comparison if(p == nullptr). This is no doubt causing the error you see. This is a common mistake.

Binary Tree insert function not working correctly C++

I'm working on a program that uses a binary tree. The program reads from a text file, storing each word in a binary tree alphabetically and finds how many times the word appeared in the file.
The problem I'm having is that my insert function is not working (the program crashes when attempting to run it). I don't know what's exactly wrong, but I suspect it has to do with my else statement towards the end of the function that deals with the right side of the tree.
Any help with fixing it would be appreciated.
Header File
#include <iostream>
#include <string>
using namespace std;
#ifndef TREE_H
#define TREE_H
class Tree
{
public:
Tree();
Tree(string str);
void traversal (Tree *);
void read_file();
void insert(string str);
~Tree();
private:
Tree *left;
Tree *right;
string word;
int count;
};
#endif // TREE_H
Cpp File
#include <iostream>
#include <string>
#include <fstream>
#include "tree.h"
using namespace std;
Tree::Tree()
{
left = NULL;
right = NULL;
count = 0;
}
Tree::Tree(string s)
{
word = s;
}
Tree::~Tree() { }
void Tree::read_file()
{
ifstream myfile;
myfile.open("input.txt", ios::out | ios::in | ios::binary);
if(myfile.is_open()){
while(myfile.good()) {
string buffer;
while(true) {
char c = myfile.get();
if(c == '-' || c == '\'' || isalpha(c) ){
if(isupper(c)) c = tolower(c);
buffer+=c;
}
else break;
}
if(buffer.length() >= 4){
insert(buffer);
}
}
myfile.close();
traversal(this);
}
else { cout << "Unable to open file!" << endl; }
}
void Tree::insert(string str) {
if(str.empty()){ // Also I'm debating whether I need this or not since the string
// cannot possibly be empty as it's part of the condition before
//insert is even called.
this->word = str;
count++;
}
else if(this->word == str) count++;
else if(str < this->word){
if(this->left == NULL) this->left = new Tree(str);
else this->left->insert(str);
}
else {
if(this->right == NULL) this->right = new Tree(str);
else this->right->insert(str);
}
}
void Tree::traversal(Tree *T) {
if(T != NULL) {
traversal(T->left);
cout << T->word << " (" << count << ")" << endl;
traversal(T->right);
}
}
Main
#include <iostream>
#include "tree.h"
using namespace std;
int main()
{
Tree tree;
tree.read_file();
return 0;
}
the problem is that you have 2 constructors, and the second one doesn't initialize pointers left/right to NULL.
edit you are showing properties from different objects: use
cout << T->word << " (" << T->count << ")" << endl;
since the recursive procedure doesn't works calling the member function of the received T. You could do it static, or change it
void Tree::traversal() {
if(this) {
traversal(left);
cout << word << " (" << count << ")" << endl;
traversal(right);
}
}
Personally, I do prefer this last 'style'.
Tree::Tree()
{
word.clear();
left = NULL;
right = NULL;
count = 0;
}
Tree::Tree(string s)
{
word = s;
left = NULL;
right = NULL;
count = 0;
}