Search Results

Search found 1031 results on 42 pages for 'iostream'.

Page 5/42 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • When is using stdio preferable to fstream?

    - by Karl Bielefeldt
    I work on a well-established, embedded C++ code base. We have been using a proprietary API to our filesystem. For better integration with third-party C libraries, we are currently in the process of implementing most of stdio.h and fcntl.h. I made what I thought was a non-controversial proposal that we should also implement the fstream class and encourage new C++ code to use it instead of the new (to our code base) C-style API. We already have the stdout parts of iostream available, although it is not widely used. Given a choice between using stdio and fstream, what are good reasons to choose stdio for embedded software development in C++?

    Read the article

  • Does putting types/functions inside namespace make compiler's parsing work easy?

    - by iammilind
    Retaining the names inside namespace will make compiler work less stressful!? For example: // test.cpp #include</*iostream,vector,string,map*/> class vec { /* ... */ }; Take 2 scenarios of main(): // scenario-1 using namespace std; // comment this line for scenario-2 int main () { vec obj; } For scenario-1 where using namespace std;, several type names from namespace std will come into global scope. Thus compiler will have to check against vec if any of the type is colliding with it. If it does then generate error. In scenario-2 where there is no using namespace, compiler just have to check vec with std, because that's the only symbol in global scope. I am interested to know that, shouldn't it make the compiler little faster ?

    Read the article

  • Array of pointers in C++.

    - by Theorem
    I am not understanding the output of this , #include <iostream> using namespace std; // pointers and arrays char ch1 = 'a' , ch2= 'b'; char ch3[6] = {'c', 'd', 'e', 'f', 'g' , 'h'}; char *ptr[3]; int main () { ptr[0] = &ch1 ; ptr[2] = ch3; cout << &ch1 << endl; } The out put is abcdefgh . isn't &ch1 supposed to give the address of ch1 ? I cannot make sense why the output should be abcdefgh.

    Read the article

  • What is wrong with this code for reading binary files? [on hold]

    - by qed
    What is wrong with this code for reading binary files? It compiles OK, but will not print out the file as planned, in fact, it prints nothing at all. #include <iostream> #include <fstream> int main(int argc, const char *argv[]) { if (argc < 2) { ::std::cerr << "usage: " << argv[0] << " <filename>\n"; return 1; } ::std::basic_ifstream<unsigned char> in(argv[1], ::std::ios::binary); unsigned char uc; while (in.get(uc)) { printf("%02X ", uc); } // TODO: error handling, in case the file could not be opened or read return 0; }

    Read the article

  • How to use c++0x thread in Android NDK?

    - by m-ric
    I am trying to compile this simple program with android-ndk-r8b: jni/hello_jni.cpp #include <iostream> #include <thread> void hello() { std::cout << "Hi i'm a thread!!!" << std::endl; } int main() { std::thread th(hello); th.join(); return 0; } jni/Application.mk APP_OPTIM := release APP_MODULES := hello_thread APP_STL := gnustl_static jni/Android.mk LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_CPPFLAGS += -std=c++0x -frtti LOCAL_MODULE := hello_thread LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -pthread LOCAL_SRC_FILES := hello_thread.cpp include $(BUILD_EXECUTABLE) ndk-build returns me an error arguin that 'thread' is not a member of 'std'. I issued ndk-build -n to get the compilation command and issued it alone in my shell: /home/evigier/android-ndk-r8b/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-g++ -MMD -MP -MF /home/evigier/eclipse_workspace/hello_thread/obj/local/armeabi/objs/hello_thread/hello_thread.o.d -fpic -ffunction-sections -funwind-tables -fstack-protector -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -march=armv5te -mtune=xscale -msoft-float -fno-exceptions -fno-rtti -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -I/home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include -I/home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi/include -I/home/evigier/eclipse_workspace/hello_thread/jni -DANDROID -Wa,--noexecstack -std=c++0x -frtti -O2 -DNDEBUG -g -I/home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include -c /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp -o /home/evigier/eclipse_workspace/hello_thread/obj/local/armeabi/objs/hello_thread/hello_thread.o Compile++ thumb : hello_thread <= hello_thread.cpp In file included from /home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/stdio.h:55:0, from /home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/wchar.h:33, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/cwchar:46, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/bits/postypes.h:42, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/iosfwd:42, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/ios:39, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/ostream:40, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/iostream:40, from jni/hello_thread.cpp:4: /home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/sys/types.h:124:9: error: 'uint64_t' does not name a type /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp: In function 'int main()': /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp:14:5: error: 'thread' is not a member of 'std' /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp:14:17: error: expected ';' before 'th' /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp:15:5: error: 'th' was not declared in this scope I read a lot of threads/questions about POSIX threads and C++ threads, but still cannot find my answer. My arm-linux-androideabi/include/c++/4.6/thread file defines class thread in std only: #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) They don't seem to be defined in my sdk (c++config.h). But how can I possibly turn them on safely? Do i need to compile my own toolchain to use (non-p)threads? My host computer is : Linux evigier-ThinkPad-X220 3.0.0-17-generic #30-Ubuntu SMP Thu Mar 8 20:45:39 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

    Read the article

  • Merging two XML files into one XML file using Java

    - by dmurali
    I am stuck with how to proceed with combining two different XML files(which has the same structure). When I was doing some research on it, people say that XML parsers like DOM or StAX will have to be used. But cant I do it with the regular IOStream? I am currently trying to do with the help of IOStream but this is not solving my purpose, its being more complex. For example, What I have tried is; public class GUI { public static void main(String[] args) throws Exception { // Creates file to write to Writer output = null; output = new BufferedWriter(new FileWriter("C:\\merged.xml")); String newline = System.getProperty("line.separator"); output.write(""); // Read in xml file 1 FileInputStream in = new FileInputStream("C:\\1.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.contains("<MemoryDump>")){ strLine = strLine.replace("<MemoryDump>", "xmlns:xsi"); } if (strLine.contains("</MemoryDump>")){ strLine = strLine.replace("</MemoryDump>", "xmlns:xsd"); } output.write(newline); output.write(strLine); System.out.println(strLine); } // Read in xml file 2 FileInputStream in = new FileInputStream("C:\\2.xml"); BufferedReader br1 = new BufferedReader(new InputStreamReader(in)); String strLine1; while ((strLine1 = br1.readLine()) != null) { if (strLine1.contains("<MemoryDump>")){ strLine1 = strLine1.replace("<MemoryDump>", ""); } if (strLine1.contains("</MemoryDump>")){ strLine1 = strLine1.replace("</MemoryDump>", ""); } output.write(newline); output.write(strLine1); I request you to kindly let me know how do I proceed with merging two XML files by adding additional content as well. It would be great if you could provide me some example links as well..! Thank You in Advance..! System.out.println(strLine1); } }

    Read the article

  • Conway's Game of Life - C++ and Qt

    - by Jeff Bridge
    I've done all of the layouts and have most of the code written even. But, I'm stuck in two places. 1) I'm not quite sure how to set up the timer. Am I using it correctly in the gridwindow class? And, am I used the timer functions/signals/slots correctly with the other gridwindow functions. 2) In GridWindow's timerFired() function, I'm having trouble checking/creating the vector-vectors. I wrote out in the comments in that function exactly what I am trying to do. Any help would be much appreciated. main.cpp // Main file for running the grid window application. #include <QApplication> #include "gridwindow.h" //#include "timerwindow.h" #include <stdexcept> #include <string> #include <fstream> #include <sstream> #include <iostream> void Welcome(); // Welcome Function - Prints upon running program; outputs program name, student name/id, class section. void Rules(); // Rules Function: Prints the rules for Conway's Game of Life. using namespace std; // A simple main method to create the window class and then pop it up on the screen. int main(int argc, char *argv[]) { Welcome(); // Calls Welcome function to print student/assignment info. Rules(); // Prints Conway's Game Rules. QApplication app(argc, argv); // Creates the overall windowed application. int rows = 25, cols = 35; //The number of rows & columns in the game grid. GridWindow widget(NULL,rows,cols); // Creates the actual window (for the grid). widget.show(); // Shows the window on the screen. return app.exec(); // Goes into visual loop; starts executing GUI. } // Welcome Function: Prints my name/id, my class number, the assignment, and the program name. void Welcome() { cout << endl; cout << "-------------------------------------------------------------------------------------------------" << endl; cout << "Name/ID - Gabe Audick #7681539807" << endl; cout << "Class/Assignment - CSCI-102 Disccusion 29915: Homework Assignment #4" << endl; cout << "-------------------------------------------------------------------------------------------------" << endl << endl; } // Rules Function: Prints the rules for Conway's Game of Life. void Rules() { cout << "Welcome to Conway's Game of Life." << endl; cout << "Game Rules:" << endl; cout << "\t 1) Any living cell with fewer than two living neighbours dies, as if caused by underpopulation." << endl; cout << "\t 2) Any live cell with more than three live neighbours dies, as if by overcrowding." << endl; cout << "\t 3) Any live cell with two or three live neighbours lives on to the next generation." << endl; cout << "\t 4) Any dead cell with exactly three live neighbours becomes a live cell." << endl << endl; cout << "Enjoy." << endl << endl; } gridcell.h // A header file for a class representing a single cell in a grid of cells. #ifndef GRIDCELL_H_ #define GRIDCELL_H_ #include <QPalette> #include <QColor> #include <QPushButton> #include <Qt> #include <QWidget> #include <QFrame> #include <QHBoxLayout> #include <iostream> // An enum representing the two different states a cell can have. enum CellType { DEAD, // DEAD = Dead Cell. --> Color = White. LIVE // LIVE = Living Cell. ---> Color = White. }; /* Class: GridCell. A class representing a single cell in a grid. Each cell is implemented as a QT QFrame that contains a single QPushButton. The button is sized so that it takes up the entire frame. Each cell also keeps track of what type of cell it is based on the CellType enum. */ class GridCell : public QFrame { Q_OBJECT // Macro allowing us to have signals & slots on this object. private: QPushButton* button; // The button inside the cell that gives its clickability. CellType type; // The type of cell (DEAD or LIVE.) public slots: void handleClick(); // Callback for handling a click on the current cell. void setType(CellType type); // Cell type mutator. Calls the "redrawCell" function. signals: void typeChanged(CellType type); // Signal to notify listeners when the cell type has changed. public: GridCell(QWidget *parent = NULL); // Constructor for creating a cell. Takes parent widget or default parent to NULL. virtual ~GridCell(); // Destructor. void redrawCell(); // Redraws cell: Sets new type/color. CellType getType() const; //Simple getter for the cell type. private: Qt::GlobalColor getColorForCellType(); // Helper method. Returns color that cell should be based from its value. }; #endif gridcell.cpp #include <iostream> #include "gridcell.h" #include "utility.h" using namespace std; // Constructor: Creates a grid cell. GridCell::GridCell(QWidget *parent) : QFrame(parent) { this->type = DEAD; // Default: Cell is DEAD (white). setFrameStyle(QFrame::Box); // Set the frame style. This is what gives each box its black border. this->button = new QPushButton(this); //Creates button that fills entirety of each grid cell. this->button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // Expands button to fill space. this->button->setMinimumSize(19,19); //width,height // Min height and width of button. QHBoxLayout *layout = new QHBoxLayout(); //Creates a simple layout to hold our button and add the button to it. layout->addWidget(this->button); setLayout(layout); layout->setStretchFactor(this->button,1); // Lets the buttons expand all the way to the edges of the current frame with no space leftover layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(this->button,SIGNAL(clicked()),this,SLOT(handleClick())); // Connects clicked signal with handleClick slot. redrawCell(); // Calls function to redraw (set new type for) the cell. } // Basic destructor. GridCell::~GridCell() { delete this->button; } // Accessor for the cell type. CellType GridCell::getType() const { return(this->type); } // Mutator for the cell type. Also has the side effect of causing the cell to be redrawn on the GUI. void GridCell::setType(CellType type) { this->type = type; redrawCell(); } // Handler slot for button clicks. This method is called whenever the user clicks on this cell in the grid. void GridCell::handleClick() { // When clicked on... if(this->type == DEAD) // If type is DEAD (white), change to LIVE (black). type = LIVE; else type = DEAD; // If type is LIVE (black), change to DEAD (white). setType(type); // Sets new type (color). setType Calls redrawCell() to recolor. } // Method to check cell type and return the color of that type. Qt::GlobalColor GridCell::getColorForCellType() { switch(this->type) { default: case DEAD: return Qt::white; case LIVE: return Qt::black; } } // Helper method. Forces current cell to be redrawn on the GUI. Called whenever the setType method is invoked. void GridCell::redrawCell() { Qt::GlobalColor gc = getColorForCellType(); //Find out what color this cell should be. this->button->setPalette(QPalette(gc,gc)); //Force the button in the cell to be the proper color. this->button->setAutoFillBackground(true); this->button->setFlat(true); //Force QT to NOT draw the borders on the button } gridwindow.h // A header file for a QT window that holds a grid of cells. #ifndef GRIDWINDOW_H_ #define GRIDWINDOW_H_ #include <vector> #include <QWidget> #include <QTimer> #include <QGridLayout> #include <QLabel> #include <QApplication> #include "gridcell.h" /* class GridWindow: This is the class representing the whole window that comes up when this program runs. It contains a header section with a title, a middle section of MxN cells and a bottom section with buttons. */ class GridWindow : public QWidget { Q_OBJECT // Macro to allow this object to have signals & slots. private: std::vector<std::vector<GridCell*> > cells; // A 2D vector containing pointers to all the cells in the grid. QLabel *title; // A pointer to the Title text on the window. QTimer *timer; // Creates timer object. public slots: void handleClear(); // Handler function for clicking the Clear button. void handleStart(); // Handler function for clicking the Start button. void handlePause(); // Handler function for clicking the Pause button. void timerFired(); // Method called whenever timer fires. public: GridWindow(QWidget *parent = NULL,int rows=3,int cols=3); // Constructor. virtual ~GridWindow(); // Destructor. std::vector<std::vector<GridCell*> >& getCells(); // Accessor for the array of grid cells. private: QHBoxLayout* setupHeader(); // Helper function to construct the GUI header. QGridLayout* setupGrid(int rows,int cols); // Helper function to constructor the GUI's grid. QHBoxLayout* setupButtonRow(); // Helper function to setup the row of buttons at the bottom. }; #endif gridwindow.cpp #include <iostream> #include "gridwindow.h" using namespace std; // Constructor for window. It constructs the three portions of the GUI and lays them out vertically. GridWindow::GridWindow(QWidget *parent,int rows,int cols) : QWidget(parent) { QHBoxLayout *header = setupHeader(); // Setup the title at the top. QGridLayout *grid = setupGrid(rows,cols); // Setup the grid of colored cells in the middle. QHBoxLayout *buttonRow = setupButtonRow(); // Setup the row of buttons across the bottom. QVBoxLayout *layout = new QVBoxLayout(); // Puts everything together. layout->addLayout(header); layout->addLayout(grid); layout->addLayout(buttonRow); setLayout(layout); } // Destructor. GridWindow::~GridWindow() { delete title; } // Builds header section of the GUI. QHBoxLayout* GridWindow::setupHeader() { QHBoxLayout *header = new QHBoxLayout(); // Creates horizontal box. header->setAlignment(Qt::AlignHCenter); this->title = new QLabel("CONWAY'S GAME OF LIFE",this); // Creates big, bold, centered label (title): "Conway's Game of Life." this->title->setAlignment(Qt::AlignHCenter); this->title->setFont(QFont("Arial", 32, QFont::Bold)); header->addWidget(this->title); // Adds widget to layout. return header; // Returns header to grid window. } // Builds the grid of cells. This method populates the grid's 2D array of GridCells with MxN cells. QGridLayout* GridWindow::setupGrid(int rows,int cols) { QGridLayout *grid = new QGridLayout(); // Creates grid layout. grid->setHorizontalSpacing(0); // No empty spaces. Cells should be contiguous. grid->setVerticalSpacing(0); grid->setSpacing(0); grid->setAlignment(Qt::AlignHCenter); for(int i=0; i < rows; i++) //Each row is a vector of grid cells. { std::vector<GridCell*> row; // Creates new vector for current row. cells.push_back(row); for(int j=0; j < cols; j++) { GridCell *cell = new GridCell(); // Creates and adds new cell to row. cells.at(i).push_back(cell); grid->addWidget(cell,i,j); // Adds to cell to grid layout. Column expands vertically. grid->setColumnStretch(j,1); } grid->setRowStretch(i,1); // Sets row expansion horizontally. } return grid; // Returns grid. } // Builds footer section of the GUI. QHBoxLayout* GridWindow::setupButtonRow() { QHBoxLayout *buttonRow = new QHBoxLayout(); // Creates horizontal box for buttons. buttonRow->setAlignment(Qt::AlignHCenter); // Clear Button - Clears cell; sets them all to DEAD/white. QPushButton *clearButton = new QPushButton("CLEAR"); clearButton->setFixedSize(100,25); connect(clearButton, SIGNAL(clicked()), this, SLOT(handleClear())); buttonRow->addWidget(clearButton); // Start Button - Starts game when user clicks. Or, resumes game after being paused. QPushButton *startButton = new QPushButton("START/RESUME"); startButton->setFixedSize(100,25); connect(startButton, SIGNAL(clicked()), this, SLOT(handleStart())); buttonRow->addWidget(startButton); // Pause Button - Pauses simulation of game. QPushButton *pauseButton = new QPushButton("PAUSE"); pauseButton->setFixedSize(100,25); connect(pauseButton, SIGNAL(clicked()), this, SLOT(handlePause())); buttonRow->addWidget(pauseButton); // Quit Button - Exits program. QPushButton *quitButton = new QPushButton("EXIT"); quitButton->setFixedSize(100,25); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); buttonRow->addWidget(quitButton); return buttonRow; // Returns bottom of layout. } /* SLOT method for handling clicks on the "clear" button. Receives "clicked" signals on the "Clear" button and sets all cells to DEAD. */ void GridWindow::handleClear() { for(unsigned int row=0; row < cells.size(); row++) // Loops through current rows' cells. { for(unsigned int col=0; col < cells[row].size(); col++) { GridCell *cell = cells[row][col]; // Grab the current cell & set its value to dead. cell->setType(DEAD); } } } /* SLOT method for handling clicks on the "start" button. Receives "clicked" signals on the "start" button and begins game simulation. */ void GridWindow::handleStart() { this->timer = new QTimer(this); // Creates new timer. connect(this->timer, SIGNAL(timeout()), this, SLOT(timerFired())); // Connect "timerFired" method class to the "timeout" signal fired by the timer. this->timer->start(500); // Timer to fire every 500 milliseconds. } /* SLOT method for handling clicks on the "pause" button. Receives "clicked" signals on the "pause" button and stops the game simulation. */ void GridWindow::handlePause() { this->timer->stop(); // Stops the timer. delete this->timer; // Deletes timer. } // Accessor method - Gets the 2D vector of grid cells. std::vector<std::vector<GridCell*> >& GridWindow::getCells() { return this->cells; } void GridWindow::timerFired() { // I'm not sure how to write this code. // I want to take the original vector-vector, and also make a new, empty vector-vector of the same size. // I would then go through the code below with the original vector, and apply the rules to the new vector-vector. // Finally, I would make the new vector-vecotr the original vector-vector. (That would be one step in the simulation.) cout << cells[1][2]; /* for (unsigned int m = 0; m < original.size(); m++) { for (unsigned int n = 0; n < original.at(m).size(); n++) { unsigned int neighbors = 0; //Begin counting number of neighbors. if (original[m-1][n-1].getType() == LIVE) // If a cell next to [i][j] is LIVE, add one to the neighbor count. neighbors += 1; if (original[m-1][n].getType() == LIVE) neighbors += 1; if (original[m-1][n+1].getType() == LIVE) neighbors += 1; if (original[m][n-1].getType() == LIVE) neighbors += 1; if (original[m][n+1].getType() == LIVE) neighbors += 1; if (original[m+1][n-1].getType() == LIVE) neighbors += 1; if (original[m+1][n].getType() == LIVE) neighbors += 1; if (original[m+1][n+1].getType() == LIVE) neighbors += 1; if (original[m][n].getType() == LIVE && neighbors < 2) // Apply game rules to cells: Create new, updated grid with the roundtwo vector. roundtwo[m][n].setType(LIVE); else if (original[m][n].getType() == LIVE && neighbors > 3) roundtwo[m][n].setType(DEAD); else if (original[m][n].getType() == LIVE && (neighbors == 2 || neighbors == 3)) roundtwo[m][n].setType(LIVE); else if (original[m][n].getType() == DEAD && neighbors == 3) roundtwo[m][n].setType(LIVE); } }*/ }

    Read the article

  • Floating point vs integer calculations on modern hardware

    - by maxpenguin
    I am doing some performance critical work in C++, and we are currently using integer calculations for problems that are inherently floating point because "its faster". This causes a whole lot of annoying problems and adds a lot of annoying code. Now, I remember reading about how floating point calculations were so slow approximately circa the 386 days, where I believe (IIRC) that there was an optional co-proccessor. But surely nowadays with exponentially more complex and powerful CPUs it makes no difference in "speed" if doing floating point or integer calculation? Especially since the actual calculation time is tiny compared to something like causing a pipeline stall or fetching something from main memory? I know the correct answer is to benchmark on the target hardware, what would be a good way to test this? I wrote two tiny C++ programs and compared their run time with "time" on Linux, but the actual run time is too variable (doesn't help I am running on a virtual server). Short of spending my entire day running hundreds of benchmarks, making graphs etc. is there something I can do to get a reasonable test of the relative speed? Any ideas or thoughts? Am I completely wrong? The programs I used as follows, they are not identical by any means: #include <iostream> #include <cmath> #include <cstdlib> #include <time.h> int main( int argc, char** argv ) { int accum = 0; srand( time( NULL ) ); for( unsigned int i = 0; i < 100000000; ++i ) { accum += rand( ) % 365; } std::cout << accum << std::endl; return 0; } Program 2: #include <iostream> #include <cmath> #include <cstdlib> #include <time.h> int main( int argc, char** argv ) { float accum = 0; srand( time( NULL ) ); for( unsigned int i = 0; i < 100000000; ++i ) { accum += (float)( rand( ) % 365 ); } std::cout << accum << std::endl; return 0; } Thanks in advance!

    Read the article

  • error by creating process

    - by Tyzak
    hello i want to get startet with programming with WIN32, therefore i wrote a programm that creates a process but in the line of code where i create the process the programm gets an error an dosn't work (abend). i don't know if the code in programm 1 is wrong or the code in the second programm that should be created by the first. ( I don't know if the code in the first programm after "createprocess" is right because i didn't get further with debugging, because in this line i get the error.(i tested it without the cout,waitforobject and close handle but i didn't work either )). First Programm: #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { bool ret; bool retwait; STARTUPINFO startupinfo; GetStartupInfo (&startupinfo); PROCESS_INFORMATION pro2info; ret = CreateProcess(NULL, L"D:\\betriebssystemePRA1PRO2.exe", NULL, NULL, false, CREATE_NEW_CONSOLE, NULL, NULL, &startupinfo, &pro2info); cout<<"hProcess: "<<pro2info.hProcess<<endl; cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl; retwait= WaitForSingleObject (pro2info.hProcess, 100); retwait= WaitForSingleObject (pro2info.hProcess, 100); CloseHandle (pro2info.hProcess);//prozesshandle schließen retwait= WaitForSingleObject (pro2info.hProcess, 100); ExitProcess(0); } Seconde Programm: #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { int b; b=GetCurrentProcessId(); cout<<b<<endl; cout<<"Druecken Sie Enter zum Beenden"<<endl; cin.get(); //warten bis Benutzer bestätigt Sleep (700); ExitProcess(0); cout<<"test"; } Thanks in advance

    Read the article

  • What is system() in linux

    - by Satish Patel
    I am an absolute beginner with Linux Operating system and just for fun in terminal I typed system() what happened next is as below: satish@satish-Inspiron-N5010 ~ $ system() >#include<iostream> >int main() bash: syntax error near unexpected token 'int' satish@satish-Ispiron-N5010~ $ Here I want to know that what is system() ? what is it's role here? why I got error in int main() line? What can we do with C/C++ programming in terminal?

    Read the article

  • Good style for handling constructor failure of critical object

    - by mtlphil
    I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue. I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened. Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices Method 1 - Stack allocated object, only in scope inside try block #include <iostream> #include "simplemidiout.h" int main() { try { SimpleMIDIOut myOut; //constructor will throw if MIDI device cannot be opened myOut.PlayNote(60,100); //..... //myOut goes out of scope outside this block //so basically the whole program has to be inside //this block. //On the plus side, it's on the stack so //destructor that handles object cleanup //is called automatically, more inline with RAII idiom? } catch(const std::exception& e) { std::cout << e.what() << std::endl; std::cin.ignore(); return 1; } std::cin.ignore(); return 0; } Method 2 - Pointer to object, heap allocated, nicer structured code? #include <iostream> #include "simplemidiout.h" int main() { SimpleMIDIOut *myOut; try { myOut = new SimpleMIDIOut(); } catch(const std::exception& e) { std::cout << e.what() << std::endl; delete myOut; return 1; } myOut->PlayNote(60,100); std::cin.ignore(); delete myOut; return 0; } I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it? I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.

    Read the article

  • How does extern work in c++?

    - by symfony
    This is from the <iostream>: namespace std { extern istream cin; ///< Linked to standard input extern ostream cout; ... It seems by using extern the data types defined in other namespaces will just be available?

    Read the article

  • C++ Deck and Card Class Error with bad alloc

    - by user3702164
    Just started learn to code in school. Our assignment requires us to create a card game with card,deck and hand class. I am having troubles with it now and i keep getting exception: std::bad_alloc at memory location. Here are my codes right now CardType h: #ifndef cardType_h #define cardType_h #include <string> using namespace std; class cardType{ public: void print(); int getValue() const; string getSymbol() const; string getSpecial() const; string getSuit() const; int checkSpecial(int gscore) const; cardType(); cardType(string suit,int value); private: int value; string special; string symbol; string suit; }; #endif CardType cpp: #include "cardType.h" #include <iostream> #include <string> using namespace std; void cardType::print() { cout << getSymbol() << " of " << getSuit() << ", having the value of " << getValue() << "."<< endl <<"This card's special is " << getSpecial() << endl; } int cardType::getValue() const { return value; } string cardType::getSymbol() const { return symbol; } string cardType::getSpecial() const { return special; } string cardType::getSuit() const { return suit; } cardType::cardType(){ value=0; symbol="?"; special='?'; suit='?'; } cardType::cardType(string s, int v){ suit = s; value = v; switch(v){ case 1: // Ace cards have a value of 1 and have no special type symbol="Ace"; special="None"; break; case 2: // 2 cards have a value of 2 and have no special type symbol="2"; special="None"; break; case 3: symbol="3"; // 3 cards have a value of 3 and have no special type special="None"; break; case 4: symbol="4"; // 4 cards have a value of 0 and have a special type "Reverse" which reverses the flow of the game special="Reverse"; value=0; break; case 5: symbol="5"; // 5 cards have a value of 5 and have no special type special="None"; break; case 6: symbol="6"; // 6 cards have a value of 6 and have no special type special="None"; break; case 7: symbol="7"; // 7 cards have a value of 7 and have no special type special="None"; break; case 8: symbol="8"; // 8 cards have a value of 8 and have no special type special="None"; break; case 9: symbol="9"; // 9 cards have a value of 0 and have a special type "Pass" which does not add any value to the game and lets the player skip his turn. special="Pass"; value=0; break; case 10: symbol="10"; // 10 cards have a value of 10 and have a special type "subtract" which instead of adding the 10 value to the total game it is subtracted instead. special="Subtract"; value=10; break; case 11: // Jack cards have a value of 10 and have no special type symbol="Jack"; special="None"; value=10; break; case 12: // Queens cards have a value of 10 and have no special type symbol="Queen"; special="None"; value=10; break; case 13: symbol="King"; // King cards have a value of 0 and have a special type "NinetyNine" which changes the total game score to 99 reguardless what number it was previously special="NinetyNine"; value=0; break; } } int cardType::checkSpecial(int gscore) const{ if(special=="Pass"){ return gscore; } if(special=="Reverse"){ return gscore; } if(special=="Subtract"){ return gscore - value; } if(special=="NinetyNine"){ return 99; } else{ return gscore + value; } } DeckType h: #ifndef deckType_h #define deckType_h #include "cardType.h" #include <string> using namespace std; class deckType { public: void shuffle(); cardType dealCard(); deckType(); private: cardType *deck; int current; }; #endif DeckType cpp: #include <iostream> #include "deckType.h" using namespace std; deckType::deckType() { int index = 0; int current=0; deck = new cardType[52]; string suit[] = {"Hearts","Diamonds","Clubs","Spades"}; int value[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; for ( int i = 0; i <= 3; i++ ) { for ( int j = 1; j <= 13; j++ ) { deck[index] = cardType(suit[i],value[j]); index++; } } } cardType deckType::dealCard() { return deck[current]; current++; } Main cpp : #include "deckType.h" #include <iostream> using namespace std; int main() { deckType gamedeck; cout << "1" <<endl; cardType currentCard; cout << "2" <<endl; currentCard = gamedeck.dealCard(); cout << "3" <<endl; return 0; } I keep getting bad_alloc at the currentCard = gamedeck.dealCard(); I really do not know what i have done wrong.

    Read the article

  • Making Global Struct in C++ Program

    - by mosg
    Hello world! I am trying to make global structure, which will be seen from any part of the source code. I need it for my big Qt project, where some global variables needed. Here it is: 3 files (global.h, dialog.h & main.cpp). For compilation I use Visual Studio (Visual C++). global.h #ifndef GLOBAL_H_ #define GLOBAL_H_ typedef struct TNumber { int g_nNumber; } TNum; TNum Num; #endif dialog.h #ifndef DIALOG_H_ #define DIALOG_H_ #include <iostream> #include "global.h" using namespace std; class ClassB { public: ClassB() {}; void showNumber() { Num.g_nNumber = 82; cout << "[ClassB][Change Number]: " << Num.g_nNumber << endl; } }; #endif and main.cpp #include <iostream> #include "global.h" #include "dialog.h" using namespace std; class ClassA { public: ClassA() { cout << "Hello from class A!\n"; }; void showNumber() { cout << "[ClassA]: " << Num.g_nNumber << endl; } }; int main(int argc, char **argv) { ClassA ca; ClassB cb; ca.showNumber(); cb.showNumber(); ca.showNumber(); cout << "Exit.\n"; return 0; } When I`m trying to build this little application, compilation works fine, but the linker gives me back an error: 1>dialog.obj : error LNK2005: "struct TNumber Num" (?Num@@3UTNumber@@A) already defined in main.obj Is there exists any solution? Thanks.

    Read the article

  • C++ preprocessing error in the code

    - by mkal
    #include "iostream" #include "string" using namespace std; #define AA(bb) \ string(::##bb); int main (int argc, char *argv[]) { AA(aa); } This gives me a bunch of errors but I am trying to understand this error pre.cpp:11:1: error: pasting "::" and "aa" does not give a valid preprocessing token Any ideas?

    Read the article

  • C++ Beginner - 'friend' functions and << operator overloading: What is the proper way to overload an

    - by Francisco P.
    Hello, everyone! In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is returned. Here's what I tried to do: ostream & Score::operator<< (ostream & os, Score right) { os << right.getPoints() << " " << right.scoreGetName(); return os; } Here are the errors returned: 1>c:\users\francisco\documents\feup\1a2s\prog\projecto3\projecto3\score.h(30) : error C2804: binary 'operator <<' has too many parameters (This error appears 4 times, actually) I managed to get it working by declaring the overload as a friend function: friend ostream & operator<< (ostream & os, Score right); And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member). Why does this work, yet the code describe above doesn't? Thanks for your time! Below is the full score.h /////////////////////////////////////////////////////////// // Score.h // Implementation of the Class Score // Created on: 10-Mai-2010 11:43:56 // Original author: Francisco /////////////////////////////////////////////////////////// #ifndef SCORE_H_ #define SCORE_H_ #include <string> #include <iostream> #include <iostream> using std::string; using std::ostream; class Score { public: Score(string name); Score(); virtual ~Score(); void addPoints(int n); string scoreGetName() const; int getPoints() const; void scoreSetName(string name); bool operator>(const Score right) const; ostream & operator<< (ostream & os, Score right); private: string _name; int _points; }; #endif

    Read the article

  • Problem separating C++ code in header, inline functions and code.

    - by YuppieNetworking
    Hello all, I have the simplest code that I want to separate in three files: Header file: class and struct declarations. No implementations at all. Inline functions file: implementation of inline methods in header. Code file: normal C++ code for more complicated implementations. When I was about to implement an operator[] method, I couldn't manage to compile it. Here is a minimal example that shows the same problem: Header (myclass.h): #ifndef _MYCLASS_H_ #define _MYCLASS_H_ class MyClass { public: MyClass(const int n); virtual ~MyClass(); double& operator[](const int i); double operator[](const int i) const; void someBigMethod(); private: double* arr; }; #endif /* _MYCLASS_H_ */ Inline functions (myclass-inl.h): #include "myclass.h" inline double& MyClass::operator[](const int i) { return arr[i]; } inline double MyClass::operator[](const int i) const { return arr[i]; } Code (myclass.cpp): #include "myclass.h" #include "myclass-inl.h" #include <iostream> inline MyClass::MyClass(const int n) { arr = new double[n]; } inline MyClass::~MyClass() { delete[] arr; } void MyClass::someBigMethod() { std::cout << "Hello big method that is not inlined" << std::endl; } And finally, a main to test it all: #include "myclass.h" #include <iostream> using namespace std; int main(int argc, char *argv[]) { MyClass m(123); double x = m[1]; m[1] = 1234; cout << "m[1]=" << m[1] << endl; x = x + 1; return 0; } void nothing() { cout << "hello world" << endl; } When I compile it, it says: main.cpp:(.text+0x1b): undefined reference to 'MyClass::MyClass(int)' main.cpp:(.text+0x2f): undefined reference to 'MyClass::operator[](int)' main.cpp:(.text+0x49): undefined reference to 'MyClass::operator[](int)' main.cpp:(.text+0x65): undefined reference to 'MyClass::operator[](int)' However, when I move the main method to the MyClass.cpp file, it works. Could you guys help me spot the problem? Thank you.

    Read the article

  • Need help with copy constructor for very basic implementation of singly linked lists

    - by Jesus
    Last week, we created a program that manages sets of strings, using classes and vectors. I was able to complete this 100%. This week, we have to replace the vector we used to store strings in our class with simple singly linked lists. The function basically allows users to declare sets of strings that are empty, and sets with only one element. In the main file, there is a vector whose elements are a struct that contain setName and strSet (class). HERE IS MY PROBLEM: It deals with the copy constructor of the class. When I remove/comment out the copy constructor, I can declare as many empty or single sets as I want, and output their values without a problem. But I know I will obviously need the copy constructor for when I implement the rest of the program. When I leave the copy constructor in, I can declare one set, either single or empty, and output its value. But if I declare a 2nd set, and i try to output either of the first two sets, i get a Segmentation Fault. Moreover, if i try to declare more then 2 sets, I get a Segmentation Fault. Any help would be appreciated!! Here is my code for a very basic implementation of everything: Here is the setcalc.cpp: (main file) #include <iostream> #include <cctype> #include <cstring> #include <string> #include "help.h" #include "strset2.h" using namespace std; // Declares of structure to hold all the sets defined struct setsOfStr { string nameOfSet; strSet stringSet; }; // Checks if the set name inputted is unique bool isSetNameUnique( vector<setsOfStr> strSetArr, string setName) { for(unsigned int i = 0; i < strSetArr.size(); i++) { if( strSetArr[i].nameOfSet == setName ) { return false; } } return true; } int main(int argc, char *argv[]) { char commandChoice; // Declares a vector with our declared structure as the type vector<setsOfStr> strSetVec; string setName; string singleEle; // Sets a loop that will constantly ask for a command until 'q' is typed while (1) { // declaring a set to be empty if(commandChoice == 'd') { cin >> setName; // Check that the set name inputted is unique if (isSetNameUnique(strSetVec, setName) == true) { strSet emptyStrSet; setsOfStr set1; set1.nameOfSet = setName; set1.stringSet = emptyStrSet; strSetVec.push_back(set1); } else { cerr << "ERROR: Re-declaration of set '" << setName << "'\n"; } } // declaring a set to be a singleton else if(commandChoice == 's') { cin >> setName; cin >> singleEle; // Check that the set name inputted is unique if (isSetNameUnique(strSetVec, setName) == true) { strSet singleStrSet(singleEle); setsOfStr set2; set2.nameOfSet = setName; set2.stringSet = singleStrSet; strSetVec.push_back(set2); } else { cerr << "ERROR: Re-declaration of set '" << setName << "'\n"; } } // using the output function else if(commandChoice == 'o') { cin >> setName; if(isSetNameUnique(strSetVec, setName) == false) { // loop through until the set name is matched and call output on its strSet for(unsigned int k = 0; k < strSetVec.size(); k++) { if( strSetVec[k].nameOfSet == setName ) { (strSetVec[k].stringSet).output(); } } } else { cerr << "ERROR: No such set '" << setName << "'\n"; } } // quitting else if(commandChoice == 'q') { break; } else { cerr << "ERROR: Ignoring bad command: '" << commandChoice << "'\n"; } } return 0; } Here is the strSet2.h: #ifndef _STRSET_ #define _STRSET_ #include <iostream> #include <vector> #include <string> struct node { std::string s1; node * next; }; class strSet { private: node * first; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set strSet (const strSet &copy); // Copy constructor // will implement destructor later void output() const; strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class #endif // _STRSET_ And here is the strSet2.cpp (implementation of class) #include <iostream> #include <vector> #include <string> #include "strset2.h" using namespace std; strSet::strSet() { first = NULL; } strSet::strSet(string s) { node *temp; temp = new node; temp->s1 = s; temp->next = NULL; first = temp; } strSet::strSet(const strSet& copy) { cout << "copy-cst\n"; node *n = copy.first; node *prev = NULL; while (n) { node *newNode = new node; newNode->s1 = n->s1; newNode->next = NULL; if (prev) { prev->next = newNode; } else { first = newNode; } prev = newNode; n = n->next; } } void strSet::output() const { if(first == NULL) { cout << "Empty set\n"; } else { node *temp; temp = first; while(1) { cout << temp->s1 << endl; if(temp->next == NULL) break; temp = temp->next; } } } strSet& strSet::operator = (const strSet& rtSide) { first = rtSide.first; return *this; }

    Read the article

  • How to PlaySound in C++

    - by user189748
    i try to play a music file in my coding, but failed. i have my music file in the same folder which save .cpp file. can someone help me? my code is: #include <iostream> #include <windows.h> int main() { PlaySound("kenny g.WAV", NULL, SND_ASYNC); }

    Read the article

  • C++ Vector vs Array (Time)

    - by vsha041
    I have got here two programs with me, both are doing exactly the same task. They are just setting an boolean array / vector to the value true. The program using vector takes 27 seconds to run whereas the program involving array with 5 times greater size takes less than 1 s. I would like to know the exact reason as to why there is such a major difference ? Are vectors really that inefficient ? Program using vectors #include <iostream> #include <vector> #include <ctime> using namespace std; int main(){ const int size = 2000; time_t start, end; time(&start); vector<bool> v(size); for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ v[i] = true; } } time(&end); cout<<difftime(end, start)<<" seconds."<<endl; } Runtime - 27 seconds Program using Array #include <iostream> #include <ctime> using namespace std; int main(){ const int size = 10000; // 5 times more size time_t start, end; time(&start); bool v[size]; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ v[i] = true; } } time(&end); cout<<difftime(end, start)<<" seconds."<<endl; } Runtime - < 1 seconds Platform - Visual Studio 2008 OS - Windows Vista 32 bit SP 1 Processor Intel(R) Pentium(R) Dual CPU T2370 @ 1.73GHz Memory (RAM) 1.00 GB Thanks Amare

    Read the article

  • error: expected `;' before '{' token - What is the cause?

    - by melee
    Here is my implementation file: using namespace std; #include <iostream> #include <iomanip> #include <string> #include <stack> //line 5 #include "proj05.canvas.h" //----------------Constructor----------------// Canvas::Canvas() //line 10 { Title = ""; Nrow = 0; Ncol = 0; image[][100]; // line 15 position.r = 0; position.c = 0; } //-------------------Paint------------------// line 20 void Canvas::Paint(int R, int C, char Color) { cout << "Paint to be implemented" << endl; } The errors I'm getting are these: proj05.canvas.cpp: In function 'std::istream& operator>>(std::istream&, Canvas&)': proj05.canvas.cpp:11: error: expected `;' before '{' token proj05.canvas.cpp:22: error: a function-definition is not allowed here before '{' token proj05.canvas.cpp:24: error: expected `}' at end of input proj05.canvas.cpp:24: error: expected `}' at end of input These seem like simple syntax errors, but I am not sure what's wrong. Could someone decode these for me? I'd really appreciate it, thanks for your time! EDIT Here is the definition of Canvas in my .h file: #ifndef CANVAS_H #define CANVAS_H #include <iostream> #include <iomanip> #include <string> #include <stack> class Canvas { public: Canvas(); void Paint(int R, int C, char Color); const int Nrow; const int Ncol; string Title; int image[][100]; stack<int> path; struct PixelCoordinates { unsigned int r; unsigned int c; } position; }; #endif

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >