So I need help on making the program display the linked list in only one line with nothing in between them. I also need to the use _getch(), getch() or getchar() functions not cin or something similar, the current program uses the _getch() function.
I'll provide my code, output and desired output. Thank you for the help in advance.
Code:
#include <iostream>
#include <conio.h>
#include <string>
#include <iomanip>
using namespace std;
struct Node {
std::string data{};
Node* next{ nullptr };
};
void addToList(Node*& head, Node*& tail) {
bool quit{ false };
std::string temp{};
Node* current{ nullptr };
while (!quit) {
temp = _getch();
if (temp == "quit") {
std::cout << "\tQuitting submenu.\n";
quit = true;
}
else {
// Allocate the new node here
current = new Node;
current->data = temp;
if (tail) {
tail->next = current;
tail = current;
}
else {
head = current;
tail = current;
}
std::stringstream ss;
for (current = head; current; current = current->next) {
ss << current->data;
}
std::cout << " ------------ " << std::endl;
std::cout << "|" << std::setw(12) << ss.str() << "|" << std::endl;
std::cout << " ------------ " << std::endl << std::endl;
}
}
}
int main() {
bool quit = false;
int choice = 0;
Node* head = nullptr;
Node* tail = nullptr;
while (!quit) {
std::cout << "1. add to list, 2. quit:\n";
std::cin >> choice;
switch (choice) {
case 1:
addToList(head, tail);
break;
case 2:
std::cout << "Quitting main menu.\n";
quit = true;
break;
default:
std::cout << "That is not a valid input, quitting program.\n";
quit = true;
}
}
for (auto tmp{ head }; tmp;) {
tmp = tmp->next;
delete head;
head = tmp;
}
}
Output:
------------
| 3|
------------
------------
| 334|
------------
------------
| 334345|
------------
------------
| 3343453456|
------------
Desired Output:
------------
| 3|
------------
------------
| 34|
------------
------------
| 345|
------------
------------
| 3456|
------------
CodePudding user response:
You could create the string you want to print first using a std::stringstream
, then print it on a single line, like this:
std::stringstream ss;
for (current = head; current; current = current->next) {
ss << current->data;
}
std::cout << " ------------ " << std::endl;
std::cout << "|" << std::setw(12) << ss.str() << "|" << std::endl;
std::cout << " ------------ " << std::endl << std::endl;
instead of this, which prints one line per list entry
cout << " ------------ " << endl;
for (current = head; current; current = current->next) {
std::cout << "|" << std::setw(12) << current->data << (current->next ? "" : "") << "|" << endl;
}
cout << " ------------ " << "\n\n";
Remember to add #include <sstream>
at the top too.