Может быть трудно решить эту проблему, потому что у меня много кода, и я не знаю, что мешает выводу.
Справочная информация заключается в том, что я пишу программу, которая читает строки текста из файла, анализирует строки в токены, а затем переводит токены в команды для создания различных типов «датчиков» (цифровых и аналоговых).
У меня есть две основные проблемы. Когда создается новый датчик, объект создается и указатель на объект помещается в массив. Когда информация для всех датчиков печатается, вызывается функция печати каждого объекта, на который указывает массив. Это все работает нормально, но по какой-то причине имя моего датчика всегда появляется пустым. Правильный токен анализируется и присваивается правильной части объекта, но почему-то что-то идет не так, и все имена датчиков отображаются как пустые.
Другая проблема похожа. Существует еще один массив указателей объектов SensorNode. Когда я создаю два объекта SensorNode и вызываю их функции печати через их массив, они печатаются нормально. Когда я добавляю еще два объекта sensorNode в массив и вызываю его снова, информация о двух последних печатается нормально, а информация о первых двух — все это мусор. Что там происходит, чтобы потерять этих первых двух?
Вот мой код, я знаю, что много положил, но я решил, что лучше больше, чем меньше.
Мой главный: (объект создается в инструкции switch в конце для случаев «New Sensor» и «New Node» и печатается в случае «STATUS»)
#include <iostream>
#include <fstream>
using namespace std;
#include "definitions.h"#include "system_utilities.h"#include "sensor.h"#include "sensor_node.h"
int main()
{
int val;
ifstream inFile;
char line[MAX_CMD_LINE_LENGTH];
char* token[MAX_TOKENS_ON_A_LINE];
int numtokens;
SensorNode* NodeList[MAX_NODES];
sensor* SensorList[MAX_SENSORS];
int numNodes = 0;
int numSensors = 0;
fillSystemCommandList();
inFile.open("p6input.txt", ios::in);
if(inFile.fail()) {
cout << "Could not open input file. Program terminating.\n\n";
return 0;
}
do {
inFile.getline(line, MAX_CMD_LINE_LENGTH);
line[strlen(line)+1] = '\0';
numtokens = parseCommandLine(line, token);
int t;
cout << "Number of tokens: " << numtokens << "\n";
val = getCommandNumber(token[0]);
switch(val) {
case HALT:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
cout << "Recognized command \"Halt\"";
break;
case STATUS:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
if (strcmp(token[1], "nodes") == 0) {
for (int i = 0; i < numNodes; i++) {
NodeList[i]->print();
}
}
if (strcmp(token[1], "sensors") == 0) {
for (int j = 0; j < numSensors; j++) {
SensorList[j]->print();
}
}
cout << "Recognized command \"Status\"";
break;
case TIME_CLICK:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
cout << "Recognized command \"time click\"";
break;
case NEW_SENSOR:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
if (strcmp(token[1], "digital") == 0) {
SensorList[numSensors] = new digitalSensor(token[2],convertFloatToValue(token[3]));
}
if (strcmp(token[1], "analog") == 0) {
SensorList[numSensors] = new analogSensor(token[2],convertFloatToValue(token[3]),convertIntToValue(token[4]),convertIntToValue(token[5]));
}
numSensors++;
cout << "Recognized command \"New Sensor\"";
break;
case NEW_SENSOR_NODE:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
NodeList[numNodes] = new SensorNode(token[1], convertFloatToValue(token[3]), convertFloatToValue(token[4]), convertFloatToValue(token[5]), convertIntToValue(token[2]), convertFloatToValue(token[6]));
numNodes++;
cout << "Recognized command \"New Sensor Node\"";
break;
case NEW_NETWORK:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
cout << "Recognized command \"New Network\"";
break;
case ADD_SENSOR_TO_NODE:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
cout << "Recognized command \"Add sensor to node\"";
break;
case ADD_NODE_TO_NETWORK:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
cout << "Recognized command \"Add node to network\"";
break;
case SENSOR_COMMAND:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
cout << "Recognized command \"Sensor Command\"";
break;
case UNDEFINED_COMMAND:
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
break;
default:
cout << "Undefined Command";
}
for (t=1; t <= numtokens; t++) {
free((void *)token[t-1]);
}
cout << "\n";
cout << "\n";
}
while (val != HALT);
return 0;
}
Вот мой датчик.
#ifndef __Program_6__sensor__
#define __Program_6__sensor__
#include <iostream>
class sensor {
protected:
char* SensorName;
float energyDraw;
int functioning;
int onoff;
public:
sensor(char*n, float pc);
virtual void print();
void setOK(int K);
int getOK();
void setOnOff(int n);
int getOnOff();
};
//---------
class digitalSensor : public sensor {
int reading;
public:
digitalSensor(char*n, float pc);
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};
class analogSensor : public sensor {
int Reading;
int minRead;
int maxRead;
public:
analogSensor(char *n, float pc, int mn, int mx);
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};#endif /* defined(__Program_6__sensor__) */
Части моего датчика.cpp:
#include "sensor.h"#include "definitions.h"using namespace std;
//--------SENSOR CLASS------------//
sensor::sensor(char *n, float pc) {
SensorName = (char*)malloc(strlen(n)+1);
energyDraw = pc;
functioning = WORKING;
onoff = OFF;
}
void sensor::print() {
cout << " Sensor: " << SensorName;
cout << " Power Consumption: " << energyDraw;
if (functioning == WORKING) {
cout << "\n Sensor is functioning correctly\n";
if (onoff == ON) {
cout << " Sensor is On\n";
}
if (onoff == OFF) {
cout << " Sensor is Off\n";
}
}
if (functioning == NOTWORKING) {
cout << " Sensor is not functioning correctly";
}
}
//*********DIGITAL SENSOR**********//
digitalSensor::digitalSensor(char *n, float pc) : sensor(n, pc){
reading = 0;
}
void digitalSensor::print() {
sensor::print();
if (functioning == WORKING && onoff == ON) {
cout << " Current sensor reading is: " << reading << "\n\n";
}
if (onoff == OFF) {
cout << " Current reading not available\n\n";
}
}//^^^^^^^^^^^^^ANALOG SENSOR^^^^^^^^^//
analogSensor::analogSensor(char *n, float pc, int mn, int mx) : sensor(n, pc) {
Reading = mn;
minRead = mn;
maxRead = mx;
}
void analogSensor::print() {
sensor::print();
cout << " Minimum Value: " << minRead << ". Maximum Value: " << maxRead;
if (functioning == WORKING && onoff == ON) {
cout << "\n Current sensor reading is: " << Reading << "\n\n";
}
if (functioning == WORKING && onoff == OFF) {
cout << "\n Current reading not available\n\n";
}
}
Возможно, вам это не нужно, но вот (часть) мой sensor_node.cpp
//Functions in SensorNode
SensorNode::SensorNode(char* n, float x, float y, float z, int i, float ah)
{
NodeName = (char*)malloc(strlen(n)+1);
strcpy(NodeName, n);
Node1.setx(x);
Node1.sety(y);
Node1.setz(z);
NodeID = i;
batt = ah;
func = 1;
}
void SensorNode::print()
{
cout << "\nSensor node " << NodeName << "\t ID: " << NodeID << "\n Location: ";
Node1.print();
cout << "\n Remaining battery life: " << batt << " amp hours";
if (func == 0) {
cout<< "\n Node is not functioning\n";
}
if (func == 1) {
cout <<"\n Node is functioning\n";
}
}
И мой sensor_node.h
class SensorNode {
char* NodeName;
int NodeID;
LOCATION Node1;
float batt;
int func;public:
SensorNode(char *n, float x, float y, float z, int i, float ah);
void print();
void setOK(int o);
int getOK();
void setLOC(float longi, float lat, float h);
};
И наконец, вот мой вывод! Проблема возникает в конце, когда ни один из датчиков не показывает имена, и мусор заменяет первые два узла.
Входной файл:
status sensors
status nodes
new_sensor_node "Kitchen Monitor" 41 1.5 2.5 3.5 10.0
new_sensor_node Basement 42 3.0 4.0 5.0 5.3
new_sensor digital "Window open" .2
new_sensor digital "Oven on" .5
new_sensor analog Temperature .03 0 255
new_sensor analog Humidity 3.1415926 10 20
new_sensor digital Alarm 2.0
status nodes
status sensors
new_sensor_node Garage 51 87.2 93.1 0.0 20.5
new_sensor_node Attic 52 1.1 2.2 15.3 100.75
new_sensor digital G1 1.5
new_sensor digital G2 1.5
new_sensor digital G3 1.5
new_sensor digital G4 1.5
new_sensor digital G5 1.5
new_sensor digital OOPS1 1.5
new_sensor analog OOPS2 1.5 0 31
status sensors
status nodes
new_sensor_node "Last ok node" 51 87.2 93.1 0.0 20.5
new_sensor_node "This one should not be added" 52 1.1 2.2 15.3 100.75
halt
Выход:
Number of tokens: 2
Token 1: status
Token 2: sensors
Recognized command "Status"
Number of tokens: 2
Token 1: status
Token 2: nodes
Recognized command "Status"
Number of tokens: 7
Token 1: new_sensor_node
Token 2: Kitchen Monitor
Token 3: 41
Token 4: 1.5
Token 5: 2.5
Token 6: 3.5
Token 7: 10.0
Recognized command "New Sensor Node"
Number of tokens: 7
Token 1: new_sensor_node
Token 2: Basement
Token 3: 42
Token 4: 3.0
Token 5: 4.0
Token 6: 5.0
Token 7: 5.3
Recognized command "New Sensor Node"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: Window open
Token 4: .2
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: Oven on
Token 4: .5
Recognized command "New Sensor"
Number of tokens: 6
Token 1: new_sensor
Token 2: analog
Token 3: Temperature
Token 4: .03
Token 5: 0
Token 6: 255
Recognized command "New Sensor"
Number of tokens: 6
Token 1: new_sensor
Token 2: analog
Token 3: Humidity
Token 4: 3.1415926
Token 5: 10
Token 6: 20
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: Alarm
Token 4: 2.0
Recognized command "New Sensor"
Number of tokens: 2
Token 1: status
Token 2: nodes
Sensor node Kitchen Monitor ID: 41
Location: (LONGITUDE: 1.5 ,LATITUDE: 2.5 ,HEIGHT: 3.5 )
Remaining battery life: 10 amp hours
Node is functioning
Sensor node Basement ID: 42
Location: (LONGITUDE: 3 ,LATITUDE: 4 ,HEIGHT: 5 )
Remaining battery life: 5.3 amp hours
Node is functioning
Recognized command "Status"
Number of tokens: 2
Token 1: status
Token 2: sensors
Sensor: Power Consumption: 0.2
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 0.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 0.03
Sensor is functioning correctly
Sensor is Off
Minimum Value: 0. Maximum Value: 255
Current reading not available
Sensor: Power Consumption: 3.14159
Sensor is functioning correctly
Sensor is Off
Minimum Value: 10. Maximum Value: 20
Current reading not available
Sensor: Power Consumption: 2
Sensor is functioning correctly
Sensor is Off
Current reading not available
Recognized command "Status"
Number of tokens: 7
Token 1: new_sensor_node
Token 2: Garage
Token 3: 51
Token 4: 87.2
Token 5: 93.1
Token 6: 0.0
Token 7: 20.5
Recognized command "New Sensor Node"
Number of tokens: 7
Token 1: new_sensor_node
Token 2: Attic
Token 3: 52
Token 4: 1.1
Token 5: 2.2
Token 6: 15.3
Token 7: 100.75
Recognized command "New Sensor Node"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: G1
Token 4: 1.5
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: G2
Token 4: 1.5
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: G3
Token 4: 1.5
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: G4
Token 4: 1.5
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: G5
Token 4: 1.5
Recognized command "New Sensor"
Number of tokens: 4
Token 1: new_sensor
Token 2: digital
Token 3: OOPS1
Token 4: 1.5
Recognized command "New Sensor"
Number of tokens: 6
Token 1: new_sensor
Token 2: analog
Token 3: OOPS2
Token 4: 1.5
Token 5: 0
Token 6: 31
Recognized command "New Sensor"
Number of tokens: 2
Token 1: status
Token 2: sensors
Sensor: Power Consumption: 0.2
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 0.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 0.03
Sensor is functioning correctly
Sensor is Off
Minimum Value: 0. Maximum Value: 255
Current reading not available
Sensor: Power Consumption: 3.14159
Sensor is functioning correctly
Sensor is Off
Minimum Value: 10. Maximum Value: 20
Current reading not available
Sensor: Power Consumption: 2
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Current reading not available
Sensor: Power Consumption: 1.5
Sensor is functioning correctly
Sensor is Off
Minimum Value: 0. Maximum Value: 31
Current reading not available
Recognized command "Status"
Number of tokens: 2
Token 1: status
Token 2: nodes
Sensor node \200o ID: 1064672
Location: (LONGITUDE: 1.4013e-45 ,LATITUDE: 1.5 ,HEIGHT: 7.00649e-45 )
Remaining battery life: 3.50325e-44 amp hours
Node is not functioning
Sensor node \300q ID: 1064768
Location: (LONGITUDE: 1.4013e-45 ,LATITUDE: 1.5 ,HEIGHT: 7.00649e-45 )
Remaining battery life: 3.50325e-44 amp hours
Node is not functioning
Sensor node Garage ID: 51
Location: (LONGITUDE: 87.2 ,LATITUDE: 93.1 ,HEIGHT: 0 )
Remaining battery life: 20.5 amp hours
Node is functioning
Sensor node Attic ID: 52
Location: (LONGITUDE: 1.1 ,LATITUDE: 2.2 ,HEIGHT: 15.3 )
Remaining battery life: 100.75 amp hours
Node is functioning
Recognized command "Status"
Number of tokens: 7
Token 1: new_sensor_node
Token 2: Last ok node
Token 3: 51
Token 4: 87.2
Token 5: 93.1
Token 6: 0.0
Token 7: 20.5
Recognized command "New Sensor Node"
Number of tokens: 7
Token 1: new_sensor_node
Token 2: This one should not be added
Token 3: 52
Token 4: 1.1
Token 5: 2.2
Token 6: 15.3
Token 7: 100.75
Recognized command "New Sensor Node"
Number of tokens: 1
Token 1: halt
Recognized command "Halt"
Как всегда, спасибо за любую помощь, которая может быть предложена! Извините за тонны кода.
Я решил одну проблему! Я добавил строку strcpy (SensorName, n); после моего malloc в моей инициализации датчика. Я выделял пространство, но не назначал ему аргумент
Других решений пока нет …