Исправь void readFromFile(const std::string& filename) { std::ifstream file(filename);…
- User
Исправь void readFromFile(const std::string& filename) { std::ifstream file(filename); int n = 0;
if (file.is_open()) { int identificator; int v; int id; std::string line; file >> v; for (int i = 0; i < v; i++) { nodes.addSorted(i); } getline(file, line); // Считываем пустую строку после первого числа while (getline(file, line)) { istringstream iss(line); int id; iss >> id; // Считываем id while (iss >> line) { // Перебираем строку по 2 символа if (line.find(';') != string::npos) { // Если нашли символ ';', прерываем цикл break; } int dst = line[0]-'0'; int wght = line[1]-'0'; // Выводим dst и wght cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } } file.close(); } else { std::cerr << "Enable open file" << filename << std::endl; } }.Проблема где-то в while (getline(file, line)) { istringstream iss(line); int id; iss >> id; // Считываем id
while (iss >> line) { // Перебираем строку по 2 символа if (line.find(';') != string::npos) { // Если нашли символ ';', прерываем цикл break; } int dst = line[0]-'0'; int wght = line[1]-'0'; // Выводим dst и wght cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } }, потому-что программа некорректно попарно считывает числа входного файла в переменные dst и wght. Текст входного файла выглядит так: 50 1 20 3 5 ; 1 4 90 ; 2 ; 3 ; 4 ;
- Assistant
void readFromFile(const std::string& filename) { std::ifstream file(filename); int n = 0;
if (file.is_open()) { int identificator; int v; int id; std::string line; file >> v; for (int i = 0; i < v; i++) { nodes.addSorted(i); } getline(file, line); // Считываем пустую строку после первого числа while (getline(file, line)) { std::istringstream iss(line); //исправлено iss >> id; // Считываем id while (iss >> id) { // Перебираем строку по числам int dst = id; // первое число if (!(iss >> id)) { break; // если не получается считать второе число, прерываем цикл } int wght = id; // второе число // Выводим dst и wght std::cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << std::endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } } file.close(); } else { std::cerr << "Unable to open file " << filename << std::endl; } } - User
Работает не корректно. Попробуй ещё раз
- Assistant
void readFromFile(const std::string& filename) { std::ifstream file(filename); int n = 0;
if (file.is_open()) { int identificator; int v; int id; std::string line; file >> v; for (int i = 0; i < v; i++) { nodes.addSorted(i); } getline(file, line); // Считываем пустую строку после первого числа while (getline(file, line)) { std::istringstream iss(line); iss >> id; // Считываем id std::string dataList; while (iss >> dataList) { // Перебираем строку по словам if (dataList.find(';') != std::string::npos) { // Если нашли символ ';', прерываем цикл break; } int dst = std::stoi(dataList); iss >> dataList; // Считываем следующее слово int wght = std::stoi(dataList); // Выводим dst и wght std::cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << std::endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } } file.close(); } else { std::cerr << "Unable to open file " << filename << std::endl; } } - User
Сработало корректно на строке 0 1 20 3 5 ;, но после неё зависло
- Assistant
Попробуйте использовать функцию
std::stringstreamвместоstd::istringstream. Вот обновленный код:#include <iostream> #include <fstream> #include <sstream> #include <string> void readFromFile(const std::string& filename) { std::ifstream file(filename); int n = 0; if (file.is_open()) { int identificator; int v; int id; std::string line; file >> v; for (int i = 0; i < v; i++) { nodes.addSorted(i); } getline(file, line); // Считываем пустую строку после первого числа while (getline(file, line)) { std::stringstream ss(line); ss >> id; std::string dataList; while (ss >> dataList) { if (dataList.find(';') != std::string::npos) { break; } int dst = std::stoi(dataList); ss >> dataList; int wght = std::stoi(dataList); std::cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << std::endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } } file.close(); } else { std::cerr << "Unable to open file " << filename << std::endl; } } - User
Нет, этот вариант вообще не запускается
- Assistant
Извините за ошибку. Поправляем код:
#include <iostream> #include <fstream> #include <sstream> #include <string> void readFromFile(const std::string& filename) { std::ifstream file(filename); int n = 0; if (file.is_open()) { int identificator; int v; int id; std::string line; file >> v; for (int i = 0; i < v; i++) { nodes.addSorted(i); } getline(file, line); // Считываем пустую строку после первого числа while (getline(file, line)) { std::stringstream ss(line); ss >> id; std::string dataList; bool semicolonFound = false; while (ss >> dataList && !semicolonFound) { if (dataList.find(';') != std::string::npos) { semicolonFound = true; } else { int dst = std::stoi(dataList); if (ss >> dataList) { int wght = std::stoi(dataList); std::cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << std::endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } } } } file.close(); } else { std::cerr << "Unable to open file " << filename << std::endl; } } - User
Так же сработало только на строке 0 1 20 3 5 ;
- Assistant
Извините за неудачные предыдущие попытки. Давайте попробуем другой подход. Вместо того, чтобы останавливаться на поиске символа ';', мы будем считывать два числа внутри каждого цикла и проверять наличие обоих чисел. Вот обновленный код:
#include <iostream> #include <fstream> #include <sstream> #include <string> void readFromFile(const std::string& filename) { std::ifstream file(filename); int n = 0; if (file.is_open()) { int identificator; int v; int id; std::string line; file >> v; for (int i = 0; i < v; i++) { nodes.addSorted(i); } getline(file, line); // Считываем пустую строку после первого числа while (getline(file, line)) { std::stringstream ss(line); ss >> id; int dst, wght; while (ss >> dst >> wght) { std::cout << "id: " << id << ", dst: " << dst << ", wght: " << wght << std::endl; ListNode* l = nodes.find(id); Edge e; e.dst = dst; e.wght = wght; l->adjList->addSorted(dst); l->edgesfrom.push_back(e); } } file.close(); } else { std::cerr << "Unable to open file " << filename << std::endl; } } - User
Заработало, спасибо
- Assistant
Пожалуйста, рад был помочь! Если у вас возникнут другие вопросы или потребуется помощь, не стесняйтесь обращаться. Удачи с вашим проектом!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.