Могу ли я узнать, как лучше всего решить эту проблему, так как в настоящее время я новичок в C++
Результат, который я ожидал, был примерно таким
id, title, price, date, mileage, fuel_type, transmission, engine_size, doors, colour, body_type, url, sale_date
3 ,Volkswagen Golf 1.9 TDI 11 Months MOT ,650 ,2000 ,155822 Diesel ,Manual ,1.9 ,4 ,Silver ,Hatchback ,https://www.ebay.co.uk/itm/124907646705?hash=item1d15136ef1:g:8dsAAOSwb-thRawR ,25 Sep 2021
4 ,1999 Volkswagen Golf GTi 1.8 turbo AUM engine V20 British racing green 3 door ,650 ,1999 ,178000 ,Petrol ,Manual ,1.8 ,3 ,Green ,Hatchback ,https://www.ebay.co.uk/itm/114998243091?hash=item1ac66def13:g:7y4AAOSwSEdhL~1m ,25 Sep 2021
Но результат у меня такой
3. - 0 - -858993460 - -858993460 - - - - -858993460 - - - -
4. - 1999 - 0 - -858993460 - - - - -858993460 - - - -
5. - 0 - 0 - -858993460 - - - - -858993460 - - - -
6. - 5 - 0 - -858993460 - - - - -858993460 - - - -
Я пробовал много разных способов сделать это, но я все еще пытаюсь найти способ правильно распечатать все входные данные из CSV-файла. Поскольку он может читать по идентификатору, но не может печатать все данные из строки конкретно.
Это мой код
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int sizeofLinkedList = 0;
struct Car
{
int id;
string title, fuel_type, transmission, engine_size, colour, body_type, url, sale_date;
int price;
int year;
int mileage;
int doors;
Car* nextAddress;
Car* prevAddress;
} *head, * tail;
Car* CreateNewNnode(int id, string title, int price, int year, int mileage ,string fuel_type, string transmission,
string engine_size, int doors, string colour, string body_type, string url, string sale_date) //create a newnode - use for any insert
{
Car* newnode = new Car;
newnode->id = id;
newnode->title = title;
newnode->price = price;
newnode->year = year;
newnode->mileage = mileage;
newnode->fuel_type = fuel_type;
newnode->transmission = transmission;
newnode->engine_size = engine_size;
newnode->doors = doors;
newnode->colour = colour;
newnode->body_type = body_type;
newnode->url = url;
newnode->sale_date = sale_date;
newnode->nextAddress = NULL;
newnode->prevAddress = NULL;
return newnode;
}
Car* partition(Car* head, Car* end, Car** newHead, Car** newEnd)
{
Car* pivot = end;
Car* prev = NULL, * cur = head, * tail = pivot;
while (cur != pivot)
{
if (cur->id < pivot->id)
{
if ((*newHead) == NULL)
(*newHead) = cur;
prev = cur;
cur = cur->nextAddress;
}
else
{
if (prev)
prev->nextAddress = cur->nextAddress;
Car* tmp = cur->nextAddress;
cur->nextAddress = NULL;
tail->nextAddress = cur;
tail = cur;
cur = tmp;
}
}
if ((*newHead) == NULL)
(*newHead) = pivot;
(*newEnd) = tail;
return pivot;
}
Car* getTail(Car* cur)
{
while (cur != NULL && cur->nextAddress != NULL)
cur = cur->nextAddress;
return cur;
}
Car* quickSortRecur(Car* head, Car* end)
{
if (!head || head == end)
return head;
Car* newHead = NULL, * newEnd = NULL;
Car* pivot = partition(head, end, &newHead, &newEnd);
if (newHead != pivot)
{
Car* tmp = newHead;
while (tmp->nextAddress != pivot)
tmp = tmp->nextAddress;
tmp->nextAddress = NULL;
newHead = quickSortRecur(newHead, tmp);
tmp = getTail(newHead);
tmp->nextAddress = pivot;
}
pivot->nextAddress = quickSortRecur(pivot->nextAddress, newEnd);
return newHead;
}
void quickSort(Car** headRef)
{
(*headRef) = quickSortRecur(*headRef, getTail(*headRef));
}
// Modified insertIntoASortedList to use quicksort
void insertIntoASortedList(Car* newnode)
{
// Insert new node at the end of the list
if (head == NULL)
{
head = tail = newnode;
}
else
{
tail->nextAddress = newnode;
newnode->prevAddress = tail;
tail = newnode;
}
// Sort the list using quicksort
quickSort(&head);
}
void readCsvFile() {
ifstream file("carlist(1).csv");
string line;
int id;
string title, fuel_type, transmission, engine_size, colour, body_type, url, sale_date;
int price;
int year;
int mileage;
int doors;
while (getline(file, line)) {
stringstream ss(line);
int id;
string title, fuel_type, transmission, engine_size, colour, body_type, url, sale_date;
int price;
int year;
int mileage;
int doors;
ss >> id;
getline(ss, title, ',');
ss >> price;
ss >> year;
ss >> mileage;
getline(ss, fuel_type, ',');
getline(ss, transmission, ',');
getline(ss, engine_size, ',');
ss >> doors;
getline(ss, colour, ',');
getline(ss, body_type, ',');
getline(ss, url, ',');
getline(ss, sale_date, ',');
Car* newnode = CreateNewNnode(id, title, price, year, mileage, fuel_type, transmission,
engine_size, doors, colour, body_type, url, sale_date);
insertIntoASortedList(newnode);
}
}
void SearchBasedOnPrice(int price1, int price2)
{
Car* current = head;
while (current != NULL)
{
if (current->id >= price1 && current->id <= price2)
{
cout << current->id << ". " << current->title << " - " << current->price << " - "
<< current->year << " - " << current->mileage << " - " << current->fuel_type << " - "
<< current->transmission << " - " << current->engine_size << " - " << current->doors << " - "
<< current->colour << " - " << current->body_type << " - " << current->url << " - "
<< current->sale_date << endl;
}
current = current->nextAddress;
}
cout << "List ended here!" << endl;
}
int main()
{
head = NULL;
srand(time(0));
int noOfcar, choice = 1;
int CarID, Year;
string Brand, Type, color;
int p1;
int p2;
cout << "Enter your searching p1: ";
cin >> p1;
cout << "Enter your searching p2: ";
cin >> p2;
readCsvFile();
SearchBasedOnPrice(p1, p2);
cout << endl;
int answer; string word;
cout << "Do you want to search anything from the list or not? 1 - Yes, 0 - No: ";
cin >> answer;
cin.ignore();
while (answer == 1)
{
cout << "Enter your searching p1: ";
cin >> p1;
cout << "Enter your searching p2: ";
cin >> p2;
readCsvFile();
SearchBasedOnPrice(p1, p2);
cout << "Do you want to edit anything? 1 - Yes, 0 - No: ";
cin >> answer;
int CarID;
if (answer == 1)
{
cout << "Enter your car ID: ";
cin >> CarID;
}
cout << "Do you still want to search anything from the list or not? 1 - Yes, 0 - No: ";
cin >> answer;
cin.ignore();
system("pause");
system("cls");
}
return 0;
}
Этот код неверен
ss >> id;
getline(ss, title, ',');
ss >> price;
ss >> year;
ss >> mileage;
Подумайте об этом формате id,title,price,year,mileage etc. Там четыре запятые, но приведенный выше код читает только одну запятую, так что это не может быть правильным.
Вот код, который должен работать лучше
string tmp;
getline(ss, tmp, ',');
id = stoi(tmp);
getline(ss, title, ',');
getline(ss, tmp, ',');
price = stoi(tmp);
getline(ss, tmp, ',');
year = stoi(tmp);
getline(ss, tmp, ',');
mileage = stoi(tmp);
Этот код считывает все запятые, но там, где требуется целое число, он считывает данные в строку tmp, а затем использует stoi для преобразования строки в целое число.
Когда я использую только «getline (ss, tmp, ','); id = stoi (tmp);» он может работать, но когда я следую приведенному выше коду, появляется сообщение об ошибке, в котором говорится, что abort() был вызван, и я не могу найти, почему, хотя ваш код правильный
@MysteMyzte Прерывание, вероятно, произойдет из-за того, что вы использовали stoi в строке, которую нельзя преобразовать в целое число (потому что она пуста или не является числовой). Распечатайте значение строки перед вызовом stoi и посмотрите, что получится. Это отладка, это нормальная часть программирования. Конечно, если вы умеете пользоваться отладчиком, это облегчит вам задачу.
-858993460
==0xCCCCCCCC
. Это неинициализированная переменная (в некоторых системах/настройках). Ваша функцияreadCsvFile()
не проверяет, не завершились ли большинство ваших файловых операций сбоем.