string to char*
-
const char* fileName = datum.c_str();
-
Vielen Dank Manni.. jetzt klappts
-
Kann ich hier auch ein ganzes Projekt uploaden?
Es stürzt immer ab bevor es zum 2. mal ins file schreibt. Aber ich habe mit dem debugger nicht herausgefunden woran es liegt..
-
Ja, aber bitte nur den Code den man auch braucht. Sag dann bitte noch welchen Compiler / Welche IDE du benutzt hast
-
Ich verwende VC++ 6.0, vom Compiler weis ich nichts genaueres, halt der, der bei vc++ 6 debei ist.
Das Programm stürzt ab, nachdem es im main die schleife beim ersten mal korrekt durchlaufen hat, und während dem 2. durchgang stürzts ab.
while(1 < 2) { flukeReader.GetDCVoltage(&DCVoltage, Range, outputFile); }
Hier die verschiedenen Files:
CFlukeReader.h :
#include <windows.h> #include <AFX.h> #include <stdio.h> #include <time.h> #include <iostream> using std::cin; #include <fstream> #include <assert.h> #include <direct.h> #include "CSerialPort.h" using namespace std; class CFlukeReader { public: /* * Constructor */ CFlukeReader(class CSerialPort* serialPort); /* * GetDCVoltage() Sends a command to the Fluke and gets the DC Voltage returned * The function returns if the return message contains "=>", "?>" or "!>" or if an error occurs * * @param [in] Range : 1 to 4 sets the accuracy of measurement * @param [out] DCVoltage: where the measured voltage is stored * @return TRUE, if the message returned from Fluke contains "=>" * FALSE, otherwise */ BOOL GetDCVoltage(double *DCVoltage, WORD Range, ofstream outputFile); /* * CheckConnection() sends a test command to Fluke and analyses the return message. * The function returns if the return message contains "=>", "?>" or "!>" or if an error occurs * * @return TRUE, if the message returned from Fluke contains "=>" * FALSE, otherwise */ BOOL CheckConnection (void); void IntToString(int i, string& res); private: class CSerialPort* m_serialPort; };
CSerialPort.h :
// CSerialPort.cpp : Defines the entry point for the console application. // #include <windows.h> #include <AFX.h> #include <stdio.h> #include <time.h> #include <iostream> using std::cin; #include <fstream> #include <assert.h> #include <direct.h> using namespace std; //defs #define BUFFER_SIZE 255 #define FLUKE45_START_CHAR 0x68 #define FLUKE45_END_CHAR 0x16 #define DEFAULT_BAUDRATE 9600 #ifndef __FLUKE45_H__ #define __FLUKE45_H__ class CSerialPort { public: /* * Constructor */ CSerialPort (); /* * Deconstructor */ ~CSerialPort (); /* * Open() opens the COM port and configures it with the specified parameters. * * @param [in] comPortNumber: number of COM port * @param [in] baudRate : baud rate [bit/s] * @return TRUE, if COM port has been successfully opened and configured * FALSE, otherwise */ BOOL Open (int comPortNumber, int baudRate); /* * Close() closes the COM port * * @return TRUE, if COM port has been closed successfully * FALSE, otherwise */ BOOL Close (void); /* * ReceiveData() receives receives bytes from COM port and writes them to receiveBuffer. * The function returns if bytesToReceive bytes have been received or a timeout occured. * * @param [in] bytesToReceive: number of bytes which are received before the function returns * @param [out] rxBuffer : buffer where the received bytes are written to * @param [out] bytesReceived : number of bytes which have been received * @return TRUE, if bytesToReceive bytes have been received * FALSE, otherwise */ BOOL ReceiveData(int bytesToReceive, char* rxBuffer, unsigned long* bytesReceived); /* * SendData() sends bytes from the txBuffer to the COM port * The function returns if all bytes have been sent or an error occured * * @param [in] bytesToSend: number of bytes which are sent before the function returns * @param [in] txBuffer : buffer, where the bytes to send are stored * @param [out] bytesSent : number of bytes, wich have been sent * @return TRUE, if bytesToSend have been sent * FALSE, otherwise */ BOOL SendData(int bytesToSend, char* txBuffer, unsigned long* bytesSent); private: HANDLE hComm; }; #endif
CFlukeReader.cpp :
// CSerialPort.cpp : Defines the entry point for the console application. // #include <windows.h> #include <AFX.h> #include <stdio.h> #include <time.h> #include <iostream> using std::cin; #include <fstream> #include <assert.h> #include <direct.h> using namespace std; //defs #define BUFFER_SIZE 255 #define FLUKE45_START_CHAR 0x68 #define FLUKE45_END_CHAR 0x16 #define DEFAULT_BAUDRATE 9600 #ifndef __FLUKE45_H__ #define __FLUKE45_H__ class CSerialPort { public: /* * Constructor */ CSerialPort (); /* * Deconstructor */ ~CSerialPort (); /* * Open() opens the COM port and configures it with the specified parameters. * * @param [in] comPortNumber: number of COM port * @param [in] baudRate : baud rate [bit/s] * @return TRUE, if COM port has been successfully opened and configured * FALSE, otherwise */ BOOL Open (int comPortNumber, int baudRate); /* * Close() closes the COM port * * @return TRUE, if COM port has been closed successfully * FALSE, otherwise */ BOOL Close (void); /* * ReceiveData() receives receives bytes from COM port and writes them to receiveBuffer. * The function returns if bytesToReceive bytes have been received or a timeout occured. * * @param [in] bytesToReceive: number of bytes which are received before the function returns * @param [out] rxBuffer : buffer where the received bytes are written to * @param [out] bytesReceived : number of bytes which have been received * @return TRUE, if bytesToReceive bytes have been received * FALSE, otherwise */ BOOL ReceiveData(int bytesToReceive, char* rxBuffer, unsigned long* bytesReceived); /* * SendData() sends bytes from the txBuffer to the COM port * The function returns if all bytes have been sent or an error occured * * @param [in] bytesToSend: number of bytes which are sent before the function returns * @param [in] txBuffer : buffer, where the bytes to send are stored * @param [out] bytesSent : number of bytes, wich have been sent * @return TRUE, if bytesToSend have been sent * FALSE, otherwise */ BOOL SendData(int bytesToSend, char* txBuffer, unsigned long* bytesSent); private: HANDLE hComm; }; #endif
CSerialPort.cpp :
#include "CSerialPort.h" //----------------------------------------------------------------------------- CSerialPort::CSerialPort() { hComm = INVALID_HANDLE_VALUE; } //----------------------------------------------------------------------------- CSerialPort::~CSerialPort() { Close (); } //----------------------------------------------------------------------------- BOOL CSerialPort::Open(int comPortNumber, int baudRate) { char szPort[16]; DCB dcb; COMMTIMEOUTS timeouts; if (hComm != INVALID_HANDLE_VALUE) { return (TRUE); } // open COM port wsprintf (szPort, "\\\\.\\COM%d", comPortNumber); hComm = CreateFile (szPort, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hComm == INVALID_HANDLE_VALUE) return (FALSE); // set timeout if (!GetCommTimeouts(hComm, &timeouts)) { Close (); return (FALSE); } timeouts.ReadIntervalTimeout = 0 ; // Specifies the maximum time, allowed to elapse between the arrival of two characters on the communications line. timeouts.ReadTotalTimeoutMultiplier = 1 ; // For each read operation, this value is multiplied by the requested number of bytes to be read. used to calculate the total time-out period for read operations. timeouts.ReadTotalTimeoutConstant = 3000; // For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes. timeouts.WriteTotalTimeoutMultiplier = 1000; // For each write operation, this value is multiplied by the number of bytes to be written. used to calculate the total time-out period for write operations. timeouts.WriteTotalTimeoutConstant = 1000; // For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written. Used to calculate the total time-out period for write operations. if (!SetCommTimeouts(hComm, &timeouts)) { Close (); return (FALSE); } // configure COM port ZeroMemory (&dcb, sizeof(dcb)); if (!GetCommState (hComm, &dcb)) { Close (); return (FALSE); } dcb.BaudRate = baudRate; // baud rate dcb.fBinary = TRUE; // must be true dcb.fParity = FALSE; // no parity bit dcb.fOutxCtsFlow = FALSE; // monitor clear to send dcb.ByteSize = (byte)8; // number of bits dcb.StopBits = ONESTOPBIT; // one stop bit if (!SetCommState(hComm, &dcb)) { Close (); return (FALSE); } return(TRUE); } //----------------------------------------------------------------------------- BOOL CSerialPort::Close (void) { BOOL bResult; if(hComm == INVALID_HANDLE_VALUE) { return (TRUE); } // close COM port bResult = CloseHandle(hComm); hComm = INVALID_HANDLE_VALUE; return(bResult); } //----------------------------------------------------------------------------- BOOL CSerialPort::SendData (int bytesToSend, char* txBuffer, unsigned long* bytesSent) { BOOL sendState; if (hComm == INVALID_HANDLE_VALUE) { return (FALSE); } sendState = WriteFile(hComm, txBuffer, bytesToSend, bytesSent, NULL); return (sendState); } //----------------------------------------------------------------------------- BOOL CSerialPort::ReceiveData (int bytesToReceive, char *rxBuffer, unsigned long* bytesReceived) { BOOL readState; if (hComm == INVALID_HANDLE_VALUE) { return (FALSE); } readState = ReadFile(hComm, rxBuffer, bytesToReceive, bytesReceived, NULL); return (readState); }
main.cpp:
#include <windows.h> #include <stdio.h> #include <time.h> #include <string> #include <sstream> #include <iostream> using std::endl; #include <fstream> #include <assert.h> #include <conio.h> #include <direct.h> using namespace std; //defs #define SBUFFER 255 #define RBUFFER 255 #define FT12_START_CHAR 0x68 #define FT12_END_CHAR 0x16 #define DEFAULT_BAUDRATE 9600 #include "CSerialPort.h" #include "CFlukeReader.h" void IntToString(int i, string& res); void main(int argc, char* argv[]) { unsigned int iBaud = DEFAULT_BAUDRATE; int iComPort = 0; int iBaudRate = 0; bool bNoProblems = true; bool bArgsSet = false; WORD Range = 0; CSerialPort serialPort; CFlukeReader flukeReader(&serialPort); cout << "******************************" << endl; cout << "* Welcome to Fluke 45 reader *" << endl; cout << "* (C) PSND *" << endl; cout << "******************************" << endl << endl; ///////////////////////////////////////////////////////////////////////////////////////// // PARAMETER SETZEN // ///////////////////////////////////////////////////////////////////////////////////////// // how many parameters are given (argv[0] is the program path so the user didn't type any parameter switch(argc) { //The user will be informed, how to use the sniffer case 1: cout << "How to use Fluke 45 Reader: " << endl; cout << ">Fluke_45_reader.exe <COM port> [<Baud rate>]" << endl; cout << "COM port: The COM port, where the Fluke is connected." << endl; cout << "Baud rate: 9600, 19200 or 57600, default: 9600" << endl << endl; cout << "Other Parameters:" << endl; cout << "-debug shows the messages from or to the Fluke with a time stamp" << endl; cout << "-v shows the same text, wich is also written in the log-file" << endl; cout << "-range 1-4 Range: 1: 300mV 2: 3V 3: 30V 4: 300V" << endl; cout << "-version shows the version of the Fluke reader" << endl << endl; cout << "To stop the sniffer press CTRL + C" << endl << endl; break; //try to set the com port case 2: iComPort = atoi(argv[1]); bArgsSet = true; break; //try to set Com port and baud rate case 3: iComPort = atoi(argv[1]); iBaudRate = atoi(argv[2]); bArgsSet = true; break; case 4: iComPort = atoi(argv[1]); iBaudRate = atoi(argv[2]); Range = atoi(argv[3]); bArgsSet = true; break; } //check the baud rate switch(iBaudRate) { case 9600: iBaud = 9600; cout << "Baud rate is " << iBaud << endl << endl; break; case 19200: iBaud = 19200; cout << "Baud rate is " << iBaud << endl << endl; break; case 57600: cout << "Baud rate is " << iBaud << endl << endl; break; default: if(argc == 3) { cout << "Baud rate not supported." << endl << "Allowed is: 9600, 19200 or 57600" << endl; cout << "Baud rate set to default(" << iBaud << ")" << endl << endl; } else if(argc == 2) { cout << "Baud rate not set." << endl << "Allowed is: 9600, 19200 or 57600" << endl; cout << "Baud rate set to default(" << iBaud << ")" << endl << endl; } break; } ///////////////////////////////////////////////////////////////////////////////////////// // COM PORT ÖFFNEN // ///////////////////////////////////////////////////////////////////////////////////////// if(bArgsSet) { cout << "Try to open COM" << iComPort << " ... \n\n"; //opening com port if(!serialPort.Open(iComPort,iBaud)) { cout << "COM" << iComPort << " not found - check if the serial port exists and isn't in use." << endl << endl; cout << "!!! The sniffer will exit now !!!" << endl << endl; bNoProblems = false; } flukeReader.CheckConnection(); } /* //Time Stamp File Name time_t timeStamp; tm *nun; timeStamp = time(0); nun = localtime(&timeStamp); char chTime[21]; sprintf(chTime,"%02d_%02d_%02d_%02dh_%02dm_%02ds", ((long)nun->tm_year)+1900, ((long)nun->tm_mon)+1, (long)nun->tm_mday, (long)nun->tm_hour, (long)nun->tm_min, (long)nun->tm_sec); //Filename zusammensetzen char fileName[40]; strcpy(fileName, "log_"); strcat(fileName, chTime); strcat(fileName, ".CSV"); */ ///////////////////////////////////////////////////////////////////////////////// // LOG-FILE GENERIEREN // ///////////////////////////////////////////////////////////////////////////////// int iJahr, iMonat, iTag, iStunde, iMinute, iSekunde; string jahr, monat, tag, stunde, minute, sekunde, datum; time_t sekunden = time(NULL); tm *uhr = localtime(&sekunden); iJahr = uhr->tm_year +1900; iMonat = uhr->tm_mon +1; iTag = uhr->tm_mday; iStunde = uhr->tm_hour; iMinute = uhr->tm_min; iSekunde = uhr->tm_sec; IntToString( iJahr, jahr ); IntToString( iMonat, monat ); IntToString( iTag, tag ); IntToString( iStunde, stunde ); IntToString( iMinute, minute ); IntToString( iSekunde, sekunde); datum = "log_" + jahr + "_" + monat + "_" + tag + "_" + stunde + "h_" + minute + "m_" + sekunde + "s.txt"; string fileName( datum ); //erstellt ein Textfile mit dem Namen log_<date,time>.csv ofstream outputFile; outputFile.open( datum.c_str(),ios::app ); //Filename Ausgeben cout << "Output File: " << fileName << endl; ///////////////////////////////////////////////////////////////////////////////// double DCVoltage; while(1 < 2) { flukeReader.GetDCVoltage(&DCVoltage, Range, outputFile); } outputFile.close(); //to halt the program on errors (e.g. double-click the exe) system("PAUSE"); } void IntToString(int i, string& res) { ostringstream temp; temp << i; res = temp.str(); }
-
Glaubst du, das liest sich jemand durch?
lk schrieb:
Ja, aber bitte nur den Code den man auch braucht.
TTS schrieb:
Aber ich habe mit dem debugger nicht herausgefunden woran es liegt..
Dann find wenigstens raus, welche Codestellen relevant sind.
Was man jetzt schon sehen kann: Kann es sein, dass der Code nicht von dir "geschrieben" sondern zusammenkopiert wurde?
-
TTS schrieb:
int iJahr, iMonat, iTag, iStunde, iMinute, iSekunde; string jahr, monat, tag, stunde, minute, sekunde, datum;
Definiere Deine Variablen so spät wie möglich.
time_t sekunden = time(NULL); tm *uhr = localtime(&sekunden); iJahr = uhr->tm_year +1900; iMonat = uhr->tm_mon +1; iTag = uhr->tm_mday; iStunde = uhr->tm_hour; iMinute = uhr->tm_min; iSekunde = uhr->tm_sec; IntToString( iJahr, jahr ); IntToString( iMonat, monat ); IntToString( iTag, tag ); IntToString( iStunde, stunde ); IntToString( iMinute, minute ); IntToString( iSekunde, sekunde); datum = jahr + "_" += monat + "_" += tag + "_" += stunde + "h_" += minute + "m_" += sekunde + "s.CSV"; string fileName; strcpy(fileName, datum); // Error 1
Warum Du hier += und + abwechselst, ist mir ein Rätsel.
Und das, was Du da mit strcopy versuchst, geht so:string fileName = datum;
Die ganzen anderen Stringvariablen kannst Du Dir auch sparen:
std::stringstream ss; ss << iJahr << '_' << iMonat << ..... "s.CSV"; string datum = ss.str(); ofstream outputFile( datum.c_str() );
ofstream outputFile( datum); // Error2
Das muss
fostream outputFile( datum.c_str() );
heißen. Ich hätte hier übrigens fileName statt datum erwartet.
Du solltest verstehen, wo genau der Unterschied zwischen std::string und char* ist. Dieses Verständnis ist scheinbar im Moment nicht vorhanden. Hole das bitte nach.
-
lk schrieb:
Ja, aber bitte nur den Code den man auch braucht.
Dann find wenigstens raus, welche Codestellen relevant sind.
Also, wenn du das Programm kompillieren willst, sind alle stellen relevant, wenn du mir aus dem code heraus sagen kannst was falsch ist, wirst du nur diese Funktion benötigen.
///////////////////////////////////////////////////////////////////////////// // CFluke45_ComPort message handlers // Range: 1: 300mV // Range: 2: 3V // Range: 3: 30V // Range: 4: 300V BOOL CFlukeReader::GetDCVoltage(double * DCVoltage, WORD Range, ofstream outputFile) { char MessageToFluke[80]={0}; char RecDataArray[80]={1}; CString CMessageToFluke, CReceiveData; int length_of_txmsg, NumberOfRxChar; NumberOfRxChar = 80; unsigned long bytesRead; unsigned long bytesSent; switch(Range) { case 1: strcpy(MessageToFluke, "VDC; FIXED; RANGE 1; RATE M;\x0d\x0a"); break; case 2: strcpy(MessageToFluke, "VDC; FIXED; RANGE 2; RATE M;\x0d\x0a"); break; case 3: strcpy(MessageToFluke, "VDC; FIXED; RANGE 3; RATE M;\x0d\x0a"); break; case 4: strcat(MessageToFluke, "VDC; FIXED; RANGE 4; RATE M;\x0d\x0a"); break; default: strcpy(MessageToFluke, "VDC; AUTO; RATEM;\x0d\x0a"); break; } length_of_txmsg = strlen(MessageToFluke); m_serialPort->SendData(length_of_txmsg, MessageToFluke, &bytesSent); Sleep(1000); // wait until measurement was performed (Einschwingverzögerung) m_serialPort->ReceiveData(NumberOfRxChar, RecDataArray, &bytesRead); strcpy(MessageToFluke, "MEAS1?\x0d\x0a"); length_of_txmsg = strlen(MessageToFluke); m_serialPort->SendData(length_of_txmsg, MessageToFluke, &bytesSent); m_serialPort->ReceiveData(NumberOfRxChar, RecDataArray, &bytesRead); CReceiveData = RecDataArray; if(CReceiveData.Find( "=>" ) > 0 ) { *DCVoltage = atof(RecDataArray); stringstream parser; parser.write(RecDataArray,80); // Stream mit deinen Daten füllen string line; getline(parser, line); // line enthält nun die erste Zeile getline(parser, line); // line enthält nun die zweite Zeile line += '\n'; outputFile << line << "\n"; strcpy(MessageToFluke, "VDC; AUTO; RATE M;\x0d\x0a"); length_of_txmsg = strlen(MessageToFluke); m_serialPort->SendData(length_of_txmsg, MessageToFluke, &bytesSent); m_serialPort->ReceiveData(NumberOfRxChar, RecDataArray, &bytesRead); return(TRUE); } if(CReceiveData.Find( "?>" ) > 0 ) { // Command syntax error *DCVoltage = 0; strcpy(MessageToFluke, "VDC; AUTO; RATE M;\x0d\x0a"); length_of_txmsg = strlen(MessageToFluke); m_serialPort->SendData(length_of_txmsg, MessageToFluke, &bytesSent); m_serialPort->ReceiveData(NumberOfRxChar, RecDataArray, &bytesRead); return(FALSE); } if(CReceiveData.Find( "!>" ) > 0 ) { // Command Failure *DCVoltage = 0; strcpy(MessageToFluke, "VDC; AUTO; RATE M;\x0d\x0a"); length_of_txmsg = strlen(MessageToFluke); m_serialPort->SendData(length_of_txmsg, MessageToFluke, &bytesSent); m_serialPort->ReceiveData(NumberOfRxChar, RecDataArray, &bytesRead); return(FALSE); } *DCVoltage = 0; strcpy(MessageToFluke, "VDC; AUTO; RATEM;\x0d\x0a"); length_of_txmsg = strlen(MessageToFluke); m_serialPort->SendData(length_of_txmsg, MessageToFluke, &bytesSent); m_serialPort->ReceiveData(NumberOfRxChar, RecDataArray, &bytesRead); return(FALSE); }
lk schrieb:
Was man jetzt schon sehen kann: Kann es sein, dass der Code nicht von dir "geschrieben" sondern zusammenkopiert wurde?
Nun, ich habe für einige Teile eine Vorlage bekommen aus der ich einige Stellen ableiten konnte, jedoch musste ich den grössten Teil selbst entwickeln. Bin nun auch schon mehr als ein Monat an dieser Aufgabe.
-
Habe alles schon geändert was du gesagt hast, war wohl noch alter code.
seufz schrieb:
ofstream outputFile( datum); // Error2
Das muss
fostream outputFile( datum.c_str() );
heißen. Ich hätte hier übrigens fileName statt datum erwartet.
Das habe ich vergessen zu ändern. Habs jetzt korrigiert, stürzt trotzdem immer noch ab.
seufz schrieb:
Du solltest verstehen, wo genau der Unterschied zwischen std::string und char* ist. Dieses Verständnis ist scheinbar im Moment nicht vorhanden. Hole das bitte nach.
Ja, das mit diesen char* und char[] und string ist noch ziemlich verwirrend für mich.. Werde mich mal etwas schlau machen.
-
BOOL GetDCVoltage(double *DCVoltage, WORD Range, ofstream outputFile);
streams sind nicht kopierbar...
Für was BOOL wenn C++ auch bool kennt?
Und dein GANZES Projekt will niemand kompilieren, sondern von dir ein möglichst am Original gehaltenes Beispiel, das deinen Fehler (beim Kompilieren oder zur Laufzeit) reproduzieren lässt, damit man auch gezielt helfen kann. Hat den wunderbaren Nebeneffekt, dass du dich selber noch mal ausgiebig mit dem Code beschäfitgen musst und einiges dabei lernen kannst.
-
l'abra d'or schrieb:
BOOL GetDCVoltage(double *DCVoltage, WORD Range, ofstream outputFile);
streams sind nicht kopierbar...
Danke, das wars. Wusste nicht, dass man streams nicht kopieren kann, hab nun einen Pointer darauf gemacht jetzt stürzt es nicht mehr ab.
-
TTS schrieb:
Danke, das wars. Wusste nicht, dass man streams nicht kopieren kann, hab nun einen Pointer darauf gemacht jetzt stürzt es nicht mehr ab.
Hier wäre statt nem Pointer eine Referenz besser (Bedeutung, Sicherheit und Handling). Und wenn das tatsächlich einen Laufzeitfehler (Absturz) produziert hat, würde ich sofort den Compiler wechseln, denn das dürfte nicht mal kompilieren!
-
Moment..
zwar stürzt es nicht mehr ab, jedoch wird nichts mehr in das File geschrieben.. hier die Definition der Funktion:
BOOL GetDCVoltage(double *DCVoltage, WORD Range, ofstream *outputFile); //Funktionsdefinition im Headefile
BOOL CFlukeReader::GetDCVoltage(double * DCVoltage, WORD Range, ofstream *outputFile) // Implementation der Funktion (gekürzt) { stringstream parser; parser.write(RecDataArray,80); // Stream mit deinen Daten füllen string line; getline(parser, line); // line enthält nun die erste Zeile getline(parser, line); // line enthält nun die zweite Zeile line += '\n'; *outputFile << line << "\n"; //Hier sollte line in über den Pointer in das File geschrieben werden }
//Main ofstream outputFile( fileName.c_str(), ios::app); //Hier wird der Stream generiert flukeReader.GetDCVoltage(&DCVoltage, Range, &outputFile); // Funktionsaufruf
-
l'abra d'or schrieb:
Hier wäre statt nem Pointer eine Referenz besser (Bedeutung, Sicherheit und Handling). Und wenn das tatsächlich einen Laufzeitfehler (Absturz) produziert hat, würde ich sofort den Compiler wechseln, denn das dürfte nicht mal kompilieren!
Wie würde man das denn mit einer Referenz statt einem Pointer lösen?
Compiler wechseln geht nicht.. das Geschäft besteht auf vc++ 6.. mit standardcompiler
-
TTS schrieb:
Wie würde man das denn mit einer Referenz statt einem Pointer lösen
BOOL CFlukeReader::GetDCVoltage(double * DCVoltage, WORD Range, ofstream &outputFile) // Implementation der Funktion (gekürzt) { stringstream parser; parser.write(RecDataArray,80); // Stream mit deinen Daten füllen string line; getline(parser, line); // line enthält nun die erste Zeile getline(parser, line); // line enthält nun die zweite Zeile line += '\n'; outputFile << line << "\n"; }
Geht also nur über Änderung der Signatur deiner Funktion. Und das "double* DCVoltage" könntest du im selben Schritt auch noch als Referenz übergeben. Damit verhinderst du, dass irgendjemand ein "NULL" übergibt - und damit nen SegFault provoziert - ein Zeiger als Parameter erlaubt dies und legt es sogar nahe, worauf du aber gar nicht eingerichtet bist.
Und jetzt poste doch mal bitte ein minimales (!!!) kompilierbares Beispiel, das bei dir zu dem Problem führt. Hier hat niemand große Lust, den gewaltigen Quelltext, der sich nichtmal übersetzen lässt, nach möglichen Problemen und Nebeneffekten zu durchsuchen.
-
Danke. Habs geschnallt mit der Referenz, es läuft nun alles i.o. Jeoch wenn ich hinter dem string der ins CSV File geschrieben werden soll ein << endl; anfüge fügt es mir eine leere Zeile ein. Wenn ich hingegen ein \n anfüge wird gar nichts mehr ins File geschrieben.
outputFile << line << endl; // Ergibt 1 leere Zeile zwischen den Einträgen outputFile << line << "\n"; // Gibt nichts aus
Sowohl die Ausgabe des Zeichens "\n" als auch die Verwendung des Manipulators "::std::endl" bewirken die Ausgabe eines Neuzeilenzeichens. Das "::std::endl" (end line ) bewirkt zusätzlich danach eine Synchronisation : Alle vorübergehend noch zwischengespeicherten Daten werden dabei tatsächlich ausgegeben.
Ich vermute es hat etwas mit dem zu tun, jedoch komme ich einfach nicht auf die Lösung, wenn ich eine normale Textdatei nehme statt ein CSV File, fügt es mir nicht noch leere Zeilen dazwischen.
Weis jemand genauer an was es liegt?
-
TTS schrieb:
wenn ich eine normale Textdatei nehme statt ein CSV File, fügt es mir nicht noch leere Zeilen dazwischen.
std::fstream kennt kein csv. Die Formatierung deines csv nimmst du selber vor. Wenn also mit csv gegenüber einer normalen Textdatei Probleme auftauchen, liegt es an deinem Code.
Einen Unterschied im Ergebnis zwischen std::endl und "\n" sehe ich hier nicht - jedenfalls bei deinem Beispielcode aus dem anderen Thread. Kann es vllt. sein dass du zu viel reinschreibst? In regelmäßigen Abständen ein std::flush(stream) wäre ein guter Versuch.
-
Nun, ich weis auch nicht was das Problem war, auf jeden Fall bein "\n" gab es nichts aus bei << endl; gab es mir eine leere Zeile dazwischen aus.
Bin auch gerade auf das flush gestossen. Das war die richtige lösung