Search Results

Search found 113 results on 5 pages for 'ofstream'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Variable not accessible within an if statment

    - by Chris
    I have a variable which holds a score for a game. My variable is accessible and correct outside of an if statement but not inside as shown below score is declared at the top of the main.cpp and calculated in the display function which also contains the code below cout << score << endl; //works if(!justFinished){ cout << score << endl; // doesn't work prints a large negative number endTime = time(NULL); ifstream highscoreFile; highscoreFile.open("highscores.txt"); if(highscoreFile.good()){ highscoreFile.close(); }else{ std::ofstream outfile ("highscores.txt"); cout << score << endl; outfile << score << std::endl; outfile.close(); } justFinished = true; } cout << score << endl;//works

    Read the article

  • What should be the potential reason to get runtime error for this program?

    - by MiNdFrEaK
    #include<iostream> #include<stack> #include<vector> #include<string> #include<fstream> #include<cstdlib> /*farnaws,C++,673,08/12/2012*/ using namespace std; string verifier(string input_line) { stack <char> braces; for(int i=0; i<input_line.size(); i++) { if(input_line[i]=='(' || input_line[i]=='[') { braces.push(input_line[i]); } else if(input_line[i]==')' || input_line[i]==']') { braces.pop(); } } if(braces.size()==0) { return "YES"; } else { return "NO"; } } int main() { ifstream file_input("input.in"); string read_file; vector<string> file_contents; if(file_input.is_open()) { while(file_input>>read_file) { file_contents.push_back(read_file); } } else { cout<<"File cant be open!"<<endl; } int limit=atoi(file_contents[0].c_str()); //cout<< limit; ofstream file_output("output.out"); if(file_output.is_open()) { for(int i=1; i<=limit; i++ ) { file_output<<verifier(file_contents[i])<<endl; } } else { cout<<"File cant be open!"<<endl; } return 0; }

    Read the article

  • Segmentation fault on returning from main (very short and simple code, no arrays or pointers)

    - by Gábor Kovács
    I've been wondering why the following trivial code produces a segmentation fault when returning from main(): //Produces "Error while dumping state (probably corrupted stack); Segmentation fault" #include <iostream> #include <fstream> #include <vector> using namespace std; class Test { vector<int> numbers; }; int main() { Test a; ifstream infile; cout << "Last statement..." << endl; // this gets executed return 0; } Interestingly, 1) if only one of the two variables is declared, I don't get the error, 2) if I declare a vector variable instead of an object with a vector member, everything's fine, 3) if I declare an ofstream instead of an ifstream, again, everything works fine. Something appears to be wrong with this specific combination... Could this be a compiler bug? I use gcc version 3.4.4 with cygwin. Thanks for the tips in advance. Gábor

    Read the article

  • Saving results to a file in C++

    - by user1680877
    I have a problem with this code. What I am looking for in the code is to get the result of "first" and "second" randomly and put the result in a file. It works great if I run it without using the file and I get all the correct results, but when I try to save the result in the file, I get only the first node which contains (first, secnd). Here is the code: #include<iostream> #include <fstream> #include<cmath> using namespace std; void main() { int first[100],secnd[100]; for (int i=0; i<100 ;i++) { first[i]=rand()%500; //random number from to 499 secnd[i]=rand()%500; //random number from to 499 ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile <<first[i]<<" "<<secnd[i]; myfile.close(); } }

    Read the article

  • How to decrease size of c++ source code? [closed]

    - by free0u
    For example #include <iostream> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n; cin >> n; for (int i = 0; i < n; i++) { cout << i; } return 0; } Decrease: #include <fstream> int main() { std::ifstream y("input.txt"); std::ofstream z("output.txt"); int n, i = 0; y >> n; while(i < n) z << i++; exit(0); } What's about "fstream"? std::fstream y("input.txt"), z("output.txt") It's amazing but output is not correct.) "output.txt" isn't remaking. Output is writing from begin of file. How to decrease code? Just for fun)

    Read the article

  • C++ read registry string value in char*

    - by Sunny
    I'm reading a registry value like this: char mydata[2048]; DWORD dataLength = sizeof(mydata); DWORD dwType = REG_SZ; ..... open key, etc ReqQueryValueEx(hKey, keyName, 0, &dwType, (BYTE*)mydata, &dataLength); My problem is, that after this, mydata content looks like: [63, 00, 3A, 00, 5C, 00...], i.e. this looks like a unicode?!?!. I need to convert this somehow to be a normal char array, without these [00], as they fail a simple logging function I have. I.e. if I call like this: WriteMessage(mydata), it outputs only "c", which is the first char in the registry. I have calls to this logging function all over the place, so I'd better of not modify it, but somehow "fix" the registry value. Here is the log function: void Logger::WriteMessage(const char *msg) { time_t now = time(0); struct tm* tm = localtime(&now); std::ofstream logFile; logFile.open(filename, std::ios::out | std::ios::app); if ( logFile.is_open() ) { logFile << tm->tm_mon << '/' << tm->tm_mday << '/' << tm->tm_year << ' '; logFile << tm->tm_hour << ':' << tm->tm_min << ':' << tm->tm_sec << "> "; logFile << msg << "\n"; logFile.close(); } }

    Read the article

  • Why won't this work; opencv Mat_<float>

    - by user1371674
    I can't seem to get this to work. I'm trying to get the pixel value of an image but first need to change the color of the image, but since I cannot use int or just Mat because the values are not whole numbers, I have to use and because of that errors pop up when I try to run this on the cmd. int main(int argc, char **argv) { Mat img = imread(argv[1]); ofstream myfile; Mat_<float> MatBlue = img; int rows1 = MatBlue.rows; int cols1 = MatBlue.cols; for(int x = 0; x < cols1; x++) { for(int y = 0; y < rows1; y++) { float val = MatBlue.at<cv::Vec3b>(y, x)[1]; MatBlue.at<cv::Vec3b>(y, x)[0] = val + 1; } } }

    Read the article

  • Variable not accessible within and if statment

    - by Chris
    I have a variable which holds a score for a game. My variable is accessible and correct outside of an if statement but not inside as shown below cout << score << endl; //works if(!justFinished){ cout << score << endl; // doesn't work prints a large negative number endTime = time(NULL); ifstream highscoreFile; highscoreFile.open("highscores.txt"); if(highscoreFile.good()){ highscoreFile.close(); }else{ std::ofstream outfile ("highscores.txt"); cout << score << endl; outfile << score << std::endl; outfile.close(); } justFinished = true; } cout << score << endl;//works

    Read the article

  • Is it possible to create ostream object, which outputs to multiple destinations?

    - by fiktor
    In 0-th approximation I have a class class MyClass{ public: ... std::ostream & getOStream(){return f;} private: ofstream f; ... }; Which is used sometimes in the following way: MyClass myclass; myclass.getOStream()<<some<<information<<printed<<here; But now I want to change the class MyClass, so that information will be printed both to f and to std::out, i.e. I want the above line to be equivalent to myclass.f<<some<<information<<printed<<here; std::cout<<some<<information<<printed<<here; I don't know any good way to do that. Do you? Is there any standard solution (for example in stl or in boost)? P.S. I tried to search on this, but it seems that I don't know good keywords. Words multiple, output, ostream, C++, boost seem to be too general.

    Read the article

  • C++: how serialize/deserialize objects without any library?

    - by Winte Winte
    I try to understand how serializing/deserializing works in c++, so I want to do that without any libs. But I really stuck with that. I start with simple objects but when I try to deserilize a vector I understand that I can't get a vector without if I don't write it size before. Moreover, I don't know which format of file I should choose because if digits will be existed before size of vector I haven't chance to read it right. However it is only the vector but I also want to do that with classes and map container. My task is serialize/deserialize a objects as this: PersonInfo { unsigned int age_; string name_; enum { undef, man, woman } sex_; } Person : PersonInfo { vector<Person> children_; map<string, PersonInfo> addrBook_; } Currently I know how to serialize simple objects in way as this: vector<PersonInfo> vecPersonInfo; vecPersonInfo.push_back(*personInfo); vecPersonInfo.push_back(*oneMorePersonInfo); ofstream file("file", ios::out | ios::binary); if (!file) { cout<<"can not open file"; } else { vector<PersonInfo>::const_iterator iterator = vecPersonInfo.begin(); for (; iterator != vecPersonInfo.end(); iterator++) { file<<*iterator; } Could you please suggest how I can do this for this conplex object or a good tutorial that explain it clearly?

    Read the article

  • Conceal packet loss in PCM stream

    - by ZeroDefect
    I am looking to use 'Packet Loss Concealment' to conceal lost PCM frames in an audio stream. Unfortunately, I cannot find a library that is accessible without all the licensing restrictions and code bloat (...up for some suggestions though). I have located some GPL code written by Steve Underwood for the Asterisk project which implements PLC. There are several limitations; although, as Steve suggests in his code, his algorithm can be applied to different streams with a bit of work. Currently, the code works with 8kHz 16-bit signed mono streams. Variations of the code can be found through a simple search of Google Code Search. My hope is that I can adapt the code to work with other streams. Initially, the goal is to adjust the algorithm for 8+ kHz, 16-bit signed, multichannel audio (all in a C++ environment). Eventually, I'm looking to make the code available under the GPL license in hopes that it could be of benefit to others... Attached is the code below with my efforts. The code includes a main function that will "drop" a number of frames with a given probability. Unfortunately, the code does not quite work as expected. I'm receiving EXC_BAD_ACCESS when running in gdb, but I don't get a trace from gdb when using 'bt' command. Clearly, I'm trampimg on memory some where but not sure exactly where. When I comment out the *amdf_pitch* function, the code runs without crashing... int main (int argc, char *argv[]) { std::ifstream fin("C:\\cc32kHz.pcm"); if(!fin.is_open()) { std::cout << "Failed to open input file" << std::endl; return 1; } std::ofstream fout_repaired("C:\\cc32kHz_repaired.pcm"); if(!fout_repaired.is_open()) { std::cout << "Failed to open output repaired file" << std::endl; return 1; } std::ofstream fout_lossy("C:\\cc32kHz_lossy.pcm"); if(!fout_lossy.is_open()) { std::cout << "Failed to open output repaired file" << std::endl; return 1; } audio::PcmConcealer Concealer; Concealer.Init(1, 16, 32000); //Generate random numbers; srand( time(NULL) ); int value = 0; int probability = 5; while(!fin.eof()) { char arr[2]; fin.read(arr, 2); //Generate's random number; value = rand() % 100 + 1; if(value <= probability) { char blank[2] = {0x00, 0x00}; fout_lossy.write(blank, 2); //Fill in data; Concealer.Fill((int16_t *)blank, 1); fout_repaired.write(blank, 2); } else { //Write data to file; fout_repaired.write(arr, 2); fout_lossy.write(arr, 2); Concealer.Receive((int16_t *)arr, 1); } } fin.close(); fout_repaired.close(); fout_lossy.close(); return 0; } PcmConcealer.hpp /* * Code adapted from Steve Underwood of the Asterisk Project. This code inherits * the same licensing restrictions as the Asterisk Project. */ #ifndef __PCMCONCEALER_HPP__ #define __PCMCONCEALER_HPP__ /** 1. What does it do? The packet loss concealment module provides a suitable synthetic fill-in signal, to minimise the audible effect of lost packets in VoIP applications. It is not tied to any particular codec, and could be used with almost any codec which does not specify its own procedure for packet loss concealment. Where a codec specific concealment procedure exists, the algorithm is usually built around knowledge of the characteristics of the particular codec. It will, therefore, generally give better results for that particular codec than this generic concealer will. 2. How does it work? While good packets are being received, the plc_rx() routine keeps a record of the trailing section of the known speech signal. If a packet is missed, plc_fillin() is called to produce a synthetic replacement for the real speech signal. The average mean difference function (AMDF) is applied to the last known good signal, to determine its effective pitch. Based on this, the last pitch period of signal is saved. Essentially, this cycle of speech will be repeated over and over until the real speech resumes. However, several refinements are needed to obtain smooth pleasant sounding results. - The two ends of the stored cycle of speech will not always fit together smoothly. This can cause roughness, or even clicks, at the joins between cycles. To soften this, the 1/4 pitch period of real speech preceeding the cycle to be repeated is blended with the last 1/4 pitch period of the cycle to be repeated, using an overlap-add (OLA) technique (i.e. in total, the last 5/4 pitch periods of real speech are used). - The start of the synthetic speech will not always fit together smoothly with the tail of real speech passed on before the erasure was identified. Ideally, we would like to modify the last 1/4 pitch period of the real speech, to blend it into the synthetic speech. However, it is too late for that. We could have delayed the real speech a little, but that would require more buffer manipulation, and hurt the efficiency of the no-lost-packets case (which we hope is the dominant case). Instead we use a degenerate form of OLA to modify the start of the synthetic data. The last 1/4 pitch period of real speech is time reversed, and OLA is used to blend it with the first 1/4 pitch period of synthetic speech. The result seems quite acceptable. - As we progress into the erasure, the chances of the synthetic signal being anything like correct steadily fall. Therefore, the volume of the synthesized signal is made to decay linearly, such that after 50ms of missing audio it is reduced to silence. - When real speech resumes, an extra 1/4 pitch period of sythetic speech is blended with the start of the real speech. If the erasure is small, this smoothes the transition. If the erasure is long, and the synthetic signal has faded to zero, the blending softens the start up of the real signal, avoiding a kind of "click" or "pop" effect that might occur with a sudden onset. 3. How do I use it? Before audio is processed, call plc_init() to create an instance of the packet loss concealer. For each received audio packet that is acceptable (i.e. not including those being dropped for being too late) call plc_rx() to record the content of the packet. Note this may modify the packet a little after a period of packet loss, to blend real synthetic data smoothly. When a real packet is not available in time, call plc_fillin() to create a sythetic substitute. That's it! */ /*! Minimum allowed pitch (66 Hz) */ #define PLC_PITCH_MIN(SAMPLE_RATE) ((double)(SAMPLE_RATE) / 66.6) /*! Maximum allowed pitch (200 Hz) */ #define PLC_PITCH_MAX(SAMPLE_RATE) ((SAMPLE_RATE) / 200) /*! Maximum pitch OLA window */ //#define PLC_PITCH_OVERLAP_MAX(SAMPLE_RATE) ((PLC_PITCH_MIN(SAMPLE_RATE)) >> 2) /*! The length over which the AMDF function looks for similarity (20 ms) */ #define CORRELATION_SPAN(SAMPLE_RATE) ((20 * (SAMPLE_RATE)) / 1000) /*! History buffer length. The buffer must also be at leat 1.25 times PLC_PITCH_MIN, but that is much smaller than the buffer needs to be for the pitch assessment. */ //#define PLC_HISTORY_LEN(SAMPLE_RATE) ((CORRELATION_SPAN(SAMPLE_RATE)) + (PLC_PITCH_MIN(SAMPLE_RATE))) namespace audio { typedef struct { /*! Consecutive erased samples */ int missing_samples; /*! Current offset into pitch period */ int pitch_offset; /*! Pitch estimate */ int pitch; /*! Buffer for a cycle of speech */ float *pitchbuf;//[PLC_PITCH_MIN]; /*! History buffer */ short *history;//[PLC_HISTORY_LEN]; /*! Current pointer into the history buffer */ int buf_ptr; } plc_state_t; class PcmConcealer { public: PcmConcealer(); ~PcmConcealer(); void Init(int channels, int bit_depth, int sample_rate); //Process a block of received audio samples. int Receive(short amp[], int frames); //Fill-in a block of missing audio samples. int Fill(short amp[], int frames); void Destroy(); private: int amdf_pitch(int min_pitch, int max_pitch, short amp[], int channel_index, int frames); void save_history(plc_state_t *s, short *buf, int channel_index, int frames); void normalise_history(plc_state_t *s); /** Holds the states of each of the channels **/ std::vector< plc_state_t * > ChannelStates; int plc_pitch_min; int plc_pitch_max; int plc_pitch_overlap_max; int correlation_span; int plc_history_len; int channel_count; int sample_rate; bool Initialized; }; } #endif PcmConcealer.cpp /* * Code adapted from Steve Underwood of the Asterisk Project. This code inherits * the same licensing restrictions as the Asterisk Project. */ #include "audio/PcmConcealer.hpp" /* We do a straight line fade to zero volume in 50ms when we are filling in for missing data. */ #define ATTENUATION_INCREMENT 0.0025 /* Attenuation per sample */ #if !defined(INT16_MAX) #define INT16_MAX (32767) #define INT16_MIN (-32767-1) #endif #ifdef WIN32 inline double rint(double x) { return floor(x + 0.5); } #endif inline short fsaturate(double damp) { if (damp > 32767.0) return INT16_MAX; if (damp < -32768.0) return INT16_MIN; return (short)rint(damp); } namespace audio { PcmConcealer::PcmConcealer() : Initialized(false) { } PcmConcealer::~PcmConcealer() { Destroy(); } void PcmConcealer::Init(int channels, int bit_depth, int sample_rate) { if(Initialized) return; if(channels <= 0 || bit_depth != 16) return; Initialized = true; channel_count = channels; this->sample_rate = sample_rate; ////////////// double min = PLC_PITCH_MIN(sample_rate); int imin = (int)min; double max = PLC_PITCH_MAX(sample_rate); int imax = (int)max; plc_pitch_min = imin; plc_pitch_max = imax; plc_pitch_overlap_max = (plc_pitch_min >> 2); correlation_span = CORRELATION_SPAN(sample_rate); plc_history_len = correlation_span + plc_pitch_min; ////////////// for(int i = 0; i < channel_count; i ++) { plc_state_t *t = new plc_state_t; memset(t, 0, sizeof(plc_state_t)); t->pitchbuf = new float[plc_pitch_min]; t->history = new short[plc_history_len]; ChannelStates.push_back(t); } } void PcmConcealer::Destroy() { if(!Initialized) return; while(ChannelStates.size()) { plc_state_t *s = ChannelStates.at(0); if(s) { if(s->history) delete s->history; if(s->pitchbuf) delete s->pitchbuf; memset(s, 0, sizeof(plc_state_t)); delete s; } ChannelStates.erase(ChannelStates.begin()); } ChannelStates.clear(); Initialized = false; } //Process a block of received audio samples. int PcmConcealer::Receive(short amp[], int frames) { if(!Initialized) return 0; int j = 0; for(int k = 0; k < ChannelStates.size(); k++) { int i; int overlap_len; int pitch_overlap; float old_step; float new_step; float old_weight; float new_weight; float gain; plc_state_t *s = ChannelStates.at(k); if (s->missing_samples) { /* Although we have a real signal, we need to smooth it to fit well with the synthetic signal we used for the previous block */ /* The start of the real data is overlapped with the next 1/4 cycle of the synthetic data. */ pitch_overlap = s->pitch >> 2; if (pitch_overlap > frames) pitch_overlap = frames; gain = 1.0 - s->missing_samples * ATTENUATION_INCREMENT; if (gain < 0.0) gain = 0.0; new_step = 1.0/pitch_overlap; old_step = new_step*gain; new_weight = new_step; old_weight = (1.0 - new_step)*gain; for (i = 0; i < pitch_overlap; i++) { int index = (i * channel_count) + j; amp[index] = fsaturate(old_weight * s->pitchbuf[s->pitch_offset] + new_weight * amp[index]); if (++s->pitch_offset >= s->pitch) s->pitch_offset = 0; new_weight += new_step; old_weight -= old_step; if (old_weight < 0.0) old_weight = 0.0; } s->missing_samples = 0; } save_history(s, amp, j, frames); j++; } return frames; } //Fill-in a block of missing audio samples. int PcmConcealer::Fill(short amp[], int frames) { if(!Initialized) return 0; int j =0; for(int k = 0; k < ChannelStates.size(); k++) { short *tmp = new short[plc_pitch_overlap_max]; int i; int pitch_overlap; float old_step; float new_step; float old_weight; float new_weight; float gain; short *orig_amp; int orig_len; orig_amp = amp; orig_len = frames; plc_state_t *s = ChannelStates.at(k); if (s->missing_samples == 0) { // As the gap in real speech starts we need to assess the last known pitch, //and prepare the synthetic data we will use for fill-in normalise_history(s); s->pitch = amdf_pitch(plc_pitch_min, plc_pitch_max, s->history + plc_history_len - correlation_span - plc_pitch_min, j, correlation_span); // We overlap a 1/4 wavelength pitch_overlap = s->pitch >> 2; // Cook up a single cycle of pitch, using a single of the real signal with 1/4 //cycle OLA'ed to make the ends join up nicely // The first 3/4 of the cycle is a simple copy for (i = 0; i < s->pitch - pitch_overlap; i++) s->pitchbuf[i] = s->history[plc_history_len - s->pitch + i]; // The last 1/4 of the cycle is overlapped with the end of the previous cycle new_step = 1.0/pitch_overlap; new_weight = new_step; for ( ; i < s->pitch; i++) { s->pitchbuf[i] = s->history[plc_history_len - s->pitch + i]*(1.0 - new_weight) + s->history[plc_history_len - 2*s->pitch + i]*new_weight; new_weight += new_step; } // We should now be ready to fill in the gap with repeated, decaying cycles // of what is in pitchbuf // We need to OLA the first 1/4 wavelength of the synthetic data, to smooth // it into the previous real data. To avoid the need to introduce a delay // in the stream, reverse the last 1/4 wavelength, and OLA with that. gain = 1.0; new_step = 1.0/pitch_overlap; old_step = new_step; new_weight = new_step; old_weight = 1.0 - new_step; for (i = 0; i < pitch_overlap; i++) { int index = (i * channel_count) + j; amp[index] = fsaturate(old_weight * s->history[plc_history_len - 1 - i] + new_weight * s->pitchbuf[i]); new_weight += new_step; old_weight -= old_step; if (old_weight < 0.0) old_weight = 0.0; } s->pitch_offset = i; } else { gain = 1.0 - s->missing_samples*ATTENUATION_INCREMENT; i = 0; } for ( ; gain > 0.0 && i < frames; i++) { int index = (i * channel_count) + j; amp[index] = s->pitchbuf[s->pitch_offset]*gain; gain -= ATTENUATION_INCREMENT; if (++s->pitch_offset >= s->pitch) s->pitch_offset = 0; } for ( ; i < frames; i++) { int index = (i * channel_count) + j; amp[i] = 0; } s->missing_samples += orig_len; save_history(s, amp, j, frames); delete [] tmp; j++; } return frames; } void PcmConcealer::save_history(plc_state_t *s, short *buf, int channel_index, int frames) { if (frames >= plc_history_len) { /* Just keep the last part of the new data, starting at the beginning of the buffer */ //memcpy(s->history, buf + len - plc_history_len, sizeof(short)*plc_history_len); int frames_to_copy = plc_history_len; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * (i + frames - plc_history_len)) + channel_index; s->history[i] = buf[index]; } s->buf_ptr = 0; return; } if (s->buf_ptr + frames > plc_history_len) { /* Wraps around - must break into two sections */ //memcpy(s->history + s->buf_ptr, buf, sizeof(short)*(plc_history_len - s->buf_ptr)); short *hist_ptr = s->history + s->buf_ptr; int frames_to_copy = plc_history_len - s->buf_ptr; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * i) + channel_index; hist_ptr[i] = buf[index]; } frames -= (plc_history_len - s->buf_ptr); //memcpy(s->history, buf + (plc_history_len - s->buf_ptr), sizeof(short)*len); frames_to_copy = frames; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * (i + (plc_history_len - s->buf_ptr))) + channel_index; s->history[i] = buf[index]; } s->buf_ptr = frames; return; } /* Can use just one section */ //memcpy(s->history + s->buf_ptr, buf, sizeof(short)*len); short *hist_ptr = s->history + s->buf_ptr; int frames_to_copy = frames; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * i) + channel_index; hist_ptr[i] = buf[index]; } s->buf_ptr += frames; } void PcmConcealer::normalise_history(plc_state_t *s) { short *tmp = new short[plc_history_len]; if (s->buf_ptr == 0) return; memcpy(tmp, s->history, sizeof(short)*s->buf_ptr); memcpy(s->history, s->history + s->buf_ptr, sizeof(short)*(plc_history_len - s->buf_ptr)); memcpy(s->history + plc_history_len - s->buf_ptr, tmp, sizeof(short)*s->buf_ptr); s->buf_ptr = 0; delete [] tmp; } int PcmConcealer::amdf_pitch(int min_pitch, int max_pitch, short amp[], int channel_index, int frames) { int i; int j; int acc; int min_acc; int pitch; pitch = min_pitch; min_acc = INT_MAX; for (i = max_pitch; i <= min_pitch; i++) { acc = 0; for (j = 0; j < frames; j++) { int index1 = (channel_count * (i+j)) + channel_index; int index2 = (channel_count * j) + channel_index; //std::cout << "Index 1: " << index1 << ", Index 2: " << index2 << std::endl; acc += abs(amp[index1] - amp[index2]); } if (acc < min_acc) { min_acc = acc; pitch = i; } } std::cout << "Pitch: " << pitch << std::endl; return pitch; } } P.S. - I must confess that digital audio is not my forte...

    Read the article

  • Unable to capture standard output of process using Boost.Process

    - by Chris Kaminski
    Currently am using Boost.Process from the Boost sandbox, and am having issues getting it to capture my standard output properly; wondering if someone can give me a second pair of eyeballs into what I might be doing wrong. I'm trying to take thumbnails out of RAW camera images using DCRAW (latest version), and capture them for conversion to QT QImage's. The process launch function: namespace bf = ::boost::filesystem; namespace bp = ::boost::process; QImage DCRawInterface::convertRawImage(string path) { // commandline: dcraw -e -c <srcfile> -> piped to stdout. if ( bf::exists( path ) ) { std::string exec = "bin\\dcraw.exe"; std::vector<std::string> args; args.push_back("-v"); args.push_back("-c"); args.push_back("-e"); args.push_back(path); bp::context ctx; ctx.stdout_behavior = bp::capture_stream(); bp::child c = bp::launch(exec, args, ctx); bp::pistream &is = c.get_stdout(); ofstream output("C:\\temp\\testcfk.jpg"); streamcopy(is, output); } return (NULL); } inline void streamcopy(std::istream& input, std::ostream& out) { char buffer[4096]; int i = 0; while (!input.eof() ) { memset(buffer, 0, sizeof(buffer)); int bytes = input.readsome(buffer, sizeof buffer); out.write(buffer, bytes); i++; } } Invoking the converter: DCRawInterface DcRaw; DcRaw.convertRawImage("test/CFK_2439.NEF"); The goal is to simply verify that I can copy the input stream to an output file. Currently, if I comment out the following line: args.push_back("-c"); then the thumbnail is written by DCRAW to the source directory with a name of CFK_2439.thumb.jpg, which proves to me that the process is getting invoked with the right arguments. What's not happening is connecting to the output pipe properly. FWIW: I'm performing this test on Windows XP under Eclipse 3.5/Latest MingW (GCC 4.4).

    Read the article

  • Compile error C++: could not deduce template argument for 'T'

    - by OneShot
    I'm trying to read binary data to load structs back into memory so I can edit them and save them back to the .dat file. readVector() attempts to read the file, and return the vectors that were serialized. But i'm getting this compile error when I try and run it. What am I doing wrong with my templates? ***** EDIT ************** Code: // Project 5.cpp : main project file. #include "stdafx.h" #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> using namespace System; using namespace std; #pragma hdrstop int checkCommand (string line); template<typename T> void writeVector(ofstream &out, const vector<T> &vec); template<typename T> vector<T> readVector(ifstream &in); struct InventoryItem { string Item; string Description; int Quantity; int wholesaleCost; int retailCost; int dateAdded; } ; int main(void) { cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl; ifstream in("data.dat"); vector<InventoryItem> structList; readVector<InventoryItem>( in ); while (1) { string line = ""; cout << endl; cout << "Commands: " << endl; cout << "1: Add a new record " << endl; cout << "2: Display a record " << endl; cout << "3: Edit a current record " << endl; cout << "4: Exit the program " << endl; cout << endl; cout << "Enter a command 1-4: "; getline(cin , line); int rValue = checkCommand(line); if (rValue == 1) { cout << "You've entered a invalid command! Try Again." << endl; } else if (rValue == 2){ cout << "Error calling command!" << endl; } else if (!rValue) { break; } } system("pause"); return 0; } int checkCommand (string line) { int intReturn = atoi(line.c_str()); int status = 3; switch (intReturn) { case 1: break; case 2: break; case 3: break; case 4: status = 0; break; default: status = 1; break; } return status; } template<typename T> void writeVector(ofstream &out, const vector<T> &vec) { out << vec.size(); for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++) { out << *i; } } ostream& operator<<(std::ostream &strm, const InventoryItem &i) { return strm << i.Item << " (" << i.Description << ")"; } template<typename T> vector<T> readVector(ifstream &in) { size_t size; in >> size; vector<T> vec; vec.reserve(size); for(int i = 0; i < size; i++) { T tmp; in >> tmp; vec.push_back(tmp); } return vec; } Compiler errors: 1>------ Build started: Project: Project 5, Configuration: Debug Win32 ------ 1>Compiling... 1>Project 5.cpp 1>.\Project 5.cpp(124) : warning C4018: '<' : signed/unsigned mismatch 1> .\Project 5.cpp(40) : see reference to function template instantiation 'std::vector<_Ty> readVector<InventoryItem>(std::ifstream &)' being compiled 1> with 1> [ 1> _Ty=InventoryItem 1> ] 1>.\Project 5.cpp(127) : error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'InventoryItem' (or there is no acceptable conversion) 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1144): could be 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,signed char *)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1146): or 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,signed char &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1148): or 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,unsigned char *)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(1150): or 'std::basic_istream<_Elem,_Traits> &std::operator >><std::char_traits<char>>(std::basic_istream<_Elem,_Traits> &,unsigned char &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(155): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::basic_istream<_Elem,_Traits> &(__cdecl *)(std::basic_istream<_Elem,_Traits> &))' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(161): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::basic_ios<_Elem,_Traits> &(__cdecl *)(std::basic_ios<_Elem,_Traits> &))' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(168): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::ios_base &(__cdecl *)(std::ios_base &))' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(175): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::_Bool &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(194): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(short &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(228): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(unsigned short &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(247): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(int &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(273): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(unsigned int &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(291): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(long &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(309): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(__w64 unsigned long &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(329): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(__int64 &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(348): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(unsigned __int64 &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(367): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(float &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(386): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(double &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(404): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(long double &)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(422): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(void *&)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\istream(441): or 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::operator >>(std::basic_streambuf<_Elem,_Traits> *)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> while trying to match the argument list '(std::ifstream, InventoryItem)' 1>Build log was saved at "file://c:\Users\Owner\Documents\Visual Studio 2008\Projects\Project 5\Project 5\Debug\BuildLog.htm" 1>Project 5 - 1 error(s), 1 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== Oh my god...I fixed that error I think and now I got another one. Will you PLEASE just help me on this one too! What the heck does this mean ??

    Read the article

  • unformatted input to a std::string instead of c-string from binary file.

    - by posop
    ok i have this program working using c-strings. I am wondering if it is possible to read in blocks of unformatted text to a std::string? I toyed arround with if >> but this reads in line by line. I've been breaking my code and banging my head against the wall trying to use std::string, so I thought it was time to enlist the experts. Here's a working program you need to supply a file "a.txt" with some content to make it run. i tried to fool around with: in.read (const_cast<char *>(memblock.c_str()), read_size); but it was acting odd. I had to do std::cout << memblock.c_str() to get it to print. and memblock.clear() did not clear out the string. anyway, if you can think of a way to use STL I would greatly appreciate it. Here's my program using c-strings // What this program does now: copies a file to a new location byte by byte // What this program is going to do: get small blocks of a file and encrypt them #include <fstream> #include <iostream> #include <string> int main (int argc, char * argv[]) { int read_size = 16; int infile_size; std::ifstream in; std::ofstream out; char * memblock; int completed = 0; memblock = new char [read_size]; in.open ("a.txt", std::ios::in | std::ios::binary | std::ios::ate); if (in.is_open()) infile_size = in.tellg(); out.open("b.txt", std::ios::out | std::ios::trunc | std::ios::binary); in.seekg (0, std::ios::beg);// get to beginning of file while(!in.eof()) { completed = completed + read_size; if(completed < infile_size) { in.read (memblock, read_size); out.write (memblock, read_size); } // end if else // last run { delete[] memblock; memblock = new char [infile_size % read_size]; in.read (memblock, infile_size % read_size + 1); out.write (memblock, infile_size % read_size ); } // end else } // end while } // main if you see anything that would make this code better please feel free to let me know.

    Read the article

  • Reading and writing C++ vector to a file

    - by JB
    For some graphics work I need to read in a large amount of data as quickly as possible and would ideally like to directly read and write the data structures to disk. Basically I have a load of 3d models in various file formats which take too long to load so I want to write them out in their "prepared" format as a cache that will load much faster on subsequent runs of the program. Is it safe to do it like this? My worries are around directly reading into the data of the vector? I've removed error checking, hard coded 4 as the size of the int and so on so that i can give a short working example, I know it's bad code, my question really is if it is safe in c++ to read a whole array of structures directly into a vector like this? I believe it to be so, but c++ has so many traps and undefined behavour when you start going low level and dealing directly with raw memory like this. I realise that number formats and sizes may change across platforms and compilers but this will only even be read and written by the same compiler program to cache data that may be needed on a later run of the same program. #include <fstream> #include <vector> using namespace std; struct Vertex { float x, y, z; }; typedef vector<Vertex> VertexList; int main() { // Create a list for testing VertexList list; Vertex v1 = {1.0f, 2.0f, 3.0f}; list.push_back(v1); Vertex v2 = {2.0f, 100.0f, 3.0f}; list.push_back(v2); Vertex v3 = {3.0f, 200.0f, 3.0f}; list.push_back(v3); Vertex v4 = {4.0f, 300.0f, 3.0f}; list.push_back(v4); // Write out a list to a disk file ofstream os ("data.dat", ios::binary); int size1 = list.size(); os.write((const char*)&size1, 4); os.write((const char*)&list[0], size1 * sizeof(Vertex)); os.close(); // Read it back in VertexList list2; ifstream is("data.dat", ios::binary); int size2; is.read((char*)&size2, 4); list2.resize(size2); // Is it safe to read a whole array of structures directly into the vector? is.read((char*)&list2[0], size2 * sizeof(Vertex)); }

    Read the article

  • c++ multithread array

    - by user1731972
    i'm doing something for fun, trying to learn multithreading Problems passing array by reference to threads but Arno pointed out that my threading via process.h wasn't going to be multi-threaded. What I'm hoping to do is something where I have an array of 100 (or 10,000, doesn't really matter I don't think), and split up the assignment of values to each thread. Example, 4 threads = 250 values per thread to be assigned. Then I can use this filled array for further calculations. Here's some code I was working on (which doesn't work) #include <process.h> #include <windows.h> #include <iostream> #include <fstream> #include <time.h> //#include <thread> using namespace std; void myThread (void *dummy ); CRITICAL_SECTION cs1,cs2; // global int main() { ofstream myfile; myfile.open ("coinToss.csv"); int rNum; long numRuns; long count = 0; int divisor = 1; float holder = 0; int counter = 0; float percent = 0.0; HANDLE hThread[1000]; int array[10000]; srand ( time(NULL) ); printf ("Runs (use multiple of 10)? "); cin >> numRuns; for (int i = 0; i < numRuns; i++) { //_beginthread( myThread, 0, (void *) (array1) ); //??? //hThread[i * 2] = _beginthread( myThread, 0, (void *) (array1) ); hThread[i*2] = _beginthread( myThread, 0, (void *) (array) ); } //WaitForMultipleObjects(numRuns * 2, hThread, TRUE, INFINITE); WaitForMultipleObjects(numRuns, hThread, TRUE, INFINITE); } void myThread (void *param ) { //thanks goes to stockoverflow //http://stackoverflow.com/questions/12801862/problems-passing-array-by-reference-to-threads int *i = (int *)param; for (int x = 0; x < 1000000; x++) { //param[x] = rand() % 2 + 1; i[x] = rand() % 2 + 1; } } Can anyone explain why it isn't working?

    Read the article

  • Tokenizing a string with variable whitespace

    - by Ron Holcomb
    I've read through a few threads detailing how to tokenize strings, but I'm apparently too thick to adapt their suggestions and solutions into my program. What I'm attempting to do is tokenize each line from a large (5k+) line file into two strings. Here's a sample of the lines: 0 -0.11639404 9.0702948e-05 0.00012207031 0.0001814059 0.051849365 0.00027210884 0.062103271 0.00036281179 0.034423828 0.00045351474 0.035125732 The difference I'm finding between my lines and the other sample input from other threads is that I have a variable amount of whitespace between the parts that I want to tokenize. Anyways, here's my attempt at tokenizing: #include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; int main(int argc, char *argv[]) { ifstream input; ofstream output; string temp2; string temp3; input.open(argv[1]); output.open(argv[2]); if (input.is_open()) { while (!input.eof()) { getline(input, temp2, ' '); while (!isspace(temp2[0])) getline(input, temp2, ' '); getline (input, temp3, '\n'); } input.close(); cout << temp2 << endl; cout << temp3 << endl; return 0; } I've clipped it some, since the troublesome bits are here. The issue that I'm having is that temp2 never seems to catch a value. Ideally, it should get populated with the first column of numbers, but it doesn't. Instead, it is blank, and temp3 is populated with the entire line. Unfortunately, in my course we haven't learned about vectors, so I'm not quite sure how to implement them in the other solutions for this I've seen, and I'd like to not just copy-paste code for assignments to get things work without actually understanding it. So, what's the extremely obvious/already been answered/simple solution I'm missing? I'd like to stick to standard libraries that g++ uses if at all possible.

    Read the article

  • C++ - Error: expected unqualified-id before ‘using’

    - by Francisco P.
    Hello, everyone. I am having some trouble on a project I'm working on. Here's the header file for the calor class: #ifndef _CALOR_ #define _CALOR_ #include "gradiente.h" using namespace std; class Calor : public Gradiente { public: Calor(); Calor(int a); ~Calor(); int getTemp(); int getMinTemp(); void setTemp(int a); void setMinTemp(int a); void mostraSensor(); }; #endif When I try to compile it: calor.h|6|error: expected unqualified-id before ‘using’| Why does this happen? I've been searching online and learned this error occurs mostly due to corrupted included files. Makes no sense to me, though. This class inherits from gradiente: #ifndef _GRADIENTE_ #define _GRADIENTE_ #include "sensor.h" using namespace std; class Gradiente : public Sensor { protected: int vActual, vMin; public: Gradiente(); ~Gradiente(); } #endif Which in turn inherits from sensor #ifndef _SENSOR_ #define _SENSOR_ #include <iostream> #include <fstream> #include <string> #include "definicoes.h" using namespace std; class Sensor { protected: int tipo; int IDsensor; bool estadoAlerta; bool estadoActivo; static int numSensores; public: Sensor(/*PARAMETROS*/); Sensor(ifstream &); ~Sensor(); int getIDsensor(); bool getEstadoAlerta(); bool getEstadoActivo(); void setEstadoAlerta(int a); void setEstadoActivo(int a); virtual void guardaSensor(ofstream &); virtual void mostraSensor(); // FUNÇÃO COMUM /* virtual int funcaoComum() = 0; virtual int funcaoComum(){return 0;};*/ }; #endif For completeness' sake, here's definicoes.h #ifndef _DEFINICOES_ #define _DEFINICOES_ const unsigned int SENSOR_MOVIMENTO = 0; const unsigned int SENSOR_SOM = 1; const unsigned int SENSOR_PRESSAO = 2; const unsigned int SENSOR_CALOR = 3; const unsigned int SENSOR_CONTACTO = 4; const unsigned int MIN_MOVIMENTO = 10; const unsigned int MIN_SOM = 10; const unsigned int MIN_PRESSAO = 10; const unsigned int MIN_CALOR = 35; #endif Any help'd be much appreciated. Thank you for your time. Thanks for your time!

    Read the article

  • Split a binary file into chunks c++

    - by L4nce0
    I've been bashing my head against trying to first divide up a file into chunks, for the purpose of sending over sockets. I can read / write a file easily without splitting it into chunks. The code below runs, works, kinda. It will write a textfile and has a garbage character. Which if this was just for txt, no problem. Jpegs aren't working with said garbage. Been at it for a few days, so I've done my research, and it's time to get some help. I do want to stick strictly to binary readers, as this need to handle any file. I've seen a lot of slick examples out there. (none of them worked for me with jpgs) Mostly something along the lines of while(file)... I subscribe to the, if you know the size, use a for-loop, not a while-loop camp. Thank you for the help!! vector<char*> readFile(const char* fn){ vector<char*> v; ifstream::pos_type size; char * memblock; ifstream file; file.open(fn,ios::in|ios::binary|ios::ate); if (file.is_open()) { size = fileS(fn); file.seekg (0, ios::beg); int bs = size/3; // arbitrary. Actual program will use the socket send size int ws = 0; int i = 0; for(i = 0; i < size; i+=bs){ if(i+bs > size) ws = size%bs; else ws = bs; memblock = new char [ws]; file.read (memblock, ws); v.push_back(memblock); } } else{ exit(-4); } return v; } int main(int argc, char **argv) { vector<char*> v = readFile("foo.txt"); ofstream myFile ("bar.txt", ios::out | ios::binary); for(vector<char*>::iterator it = v.begin(); it!=v.end(); ++it ){ myFile.write(*it,strlen(*it)); } }

    Read the article

  • boost::serialization with mutable members

    - by redmoskito
    Using boost::serialization, what's the "best" way to serialize an object that contains cached, derived values in mutable members, such that cached members aren't serialized, but on deserialization, they are initialized the their appropriate default. A definition of "best" follows later, but first an example: class Example { public: Example(float n) : num(n), sqrt_num(-1.0) {} float get_num() const { return num; } // compute and cache sqrt on first read float get_sqrt() const { if(sqrt_num < 0) sqrt_num = sqrt(num); return sqrt_num; } template <class Archive> void serialize(Archive& ar, unsigned int version) { ... } private: float num; mutable float sqrt_num; }; On serialization, only the "num" member should be saved. On deserialization, the sqrt_num member must be initialized to its sentinel value indicating it needs to be computed. What is the most elegant way to implement this? In my mind, an elegant solution would avoid splitting serialize() into separate save() and load() methods (which introduces maintenance problems). One possible implementation of serialize: template <class Archive> void serialize(Archive& ar, unsigned int version) { ar & num; sqrt_num = -1.0; } This handles the deserialization case, but in the serialization case, the cached value is killed and must be recomputed. Also, I've never seen an example of boost::serialize that explicitly sets members inside of serialize(), so I wonder if this is generally not recommended. Some might suggest that the default constructor handles this, for example: int main() { Example e; { std::ifstream ifs("filename"); boost::archive::text_iarchive ia(ifs); ia >> e; } cout << e.get_sqrt() << endl; return 0; } which works in this case, but I think fails if the object receiving the deserialized data has already been initialized, as in the example below: int main() { Example ex1(4); Example ex2(9); cout << ex1.get_sqrt() << endl; // outputs 2; cout << ex2.get_sqrt() << endl; // outputs 3; // the following two blocks should implement ex2 = ex1; // save ex1 to archive { std::ofstream ofs("filename"); boost::archive::text_oarchive oa(ofs); oa << ex1; } // read it back into ex2 { std::ifstream ifs("filename"); boost::archive::text_iarchive ia(ifs); ia >> ex2; } // these should be equal now, but aren't, // since Example::serialize() doesn't modify num_sqrt cout << ex1.get_sqrt() << endl; // outputs 2; cout << ex2.get_sqrt() << endl; // outputs 3; return 0; } I'm sure this issue has come up with others, but I have struggled to find any documentation on this particular scenario. Thanks!

    Read the article

  • Problem with reading file line-by-line

    - by Maulrus
    I'm trying to complete an exercise to write a program that takes the following command line arguments: an input file, an output file, and an unspecified number of words. The program is to read the contents of the input file line by line, find for each word given which lines contain the word, and print the lines with their line number to the output file. Here's my code: #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; int main(int argc, char* argv[]) { if (argc < 4) { cerr << "Error #1: not enough arguments provided\n"; return 1; } ifstream in(argv[1]); if (!in.is_open()) { cerr << "Error #2: input file could not be opened\n"; return 2; } ofstream out(argv[2]); if (!out.is_open()) { cerr << "Error #3: output file could not be opened\n"; return 3; } ostringstream oss; for (int i = 3; i < argc; ++i) { int k = 0; string temp; oss << argv[i] << ":\n\n"; while (getline(in, temp)) { ++k; unsigned x = temp.find(argv[i]); if (x != string::npos) oss << "Line #" << k << ": " << temp << endl; } } string copy = oss.str(); out << copy; in.close(); out.close(); return 0; } If I try to run that, I get the predicted output for the first word given, but any words following it aren't found. For example, for the source code above will give the following output: in: Line #1: #include <iostream> Line #2: #include <fstream> Line #3: #include <string> Line #4: #include <sstream> Line #5: using namespace std; Line #7: int main(int argc, char* argv[]) { Line #12: ifstream in(argv[1]); Line #13: if (!in.is_open()) { Line #14: cerr << "Error #2: input file could not be opened\n"; Line #22: ostringstream oss; Line #23: string temp; Line #24: for (int i = 3; i < argc; ++i) { Line #26: int k = 0; Line #28: while (getline(in, temp)) { Line #30: unsigned x = temp.find(argv[i]); Line #31: if (x != string::npos) Line #32: oss << "Line #" << k << ": " << temp << endl; Line #35: string copy = oss.str(); Line #37: in.close(); out: That is, it'll find all the instances of the first word given but not any following. What am I doing wrong here?

    Read the article

  • Difficulty analyzing text from a file

    - by Nikko
    I'm running into a rather amusing error with my output on this lab and I was wondering if any of you might be able to hint at where my problem lies. The goal is find the high, low, average, sum of the record, and output original record. I started with a rather basic program to solve for one record and when I achieved this I expanded the program to work with the entire text file. Initially the program would correctly output: 346 130 982 90 656 117 595 High# Low# Sum# Average# When I expanded it to work for the entire record my output stopped working how I had wanted it to. 0 0 0 0 0 0 0 High: 0 Low: 0 Sum: 0 Average: 0 0 0 0 0 0 0 0 High: 0 Low: 0 Sum: 0 Average: 0 etc... I cant quite figure out why my ifstream just completely stopped bothering to input the values from file. I'll go take a walk and take another crack at it. If that doesn't work I'll be back here to check for any responses =) Thank you! #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; int main() { int num; int high = 0; int low = 1000; double average = 0; double sum = 0; int numcount = 0; int lines = 1; char endoline; ifstream inData; ofstream outData; inData.open("c:\\Users\\Nikko\\Desktop\\record5ain.txt"); outData.open("c:\\Users\\Nikko\\Desktop\\record5aout.txt"); if(!inData) //Reminds me to change path names when working on different computers. { cout << "Could not open file, program will exit" << endl; exit(1); } while(inData.get(endoline)) { if(endoline == '\n') lines++; } for(int A = 0; A < lines; A++) { for(int B = 0; B < 7; B++) { while(inData >> num) inData >> num; numcount++; sum += num; if(num < low) low = num; if(num > high) high = num; average = sum / numcount; outData << num << '\t'; } outData << "High: " << high << " " << "Low: " << low << " " << "Sum: " << sum << " " << "Average: " << average << endl; } inData.close(); outData.close(); return(0); }

    Read the article

  • Segmentation fault, shared library

    - by user1306184
    I get Segmentation Fault when I try to run my program. Can someone please help me find out what Im doing wrong? Compiling with this: g++ sms_out.cpp -o sms_out g++ -c -fPIC SMSDispatch.cpp g++ -shared SMSDispatch.o -o libSMSDispatch.so It should be a shared library and dynamic linking. I get Segmentation Fault when I try to run sms_out. //sms_out.cpp #include <iostream> #include<cstdlib> #include<fstream> #include<sstream> #include<string> #include "SMSDispatch.h" using namespace std; string sms = ""; void sendSMS(string sms) { SMSDispatch* sPtr=0; sPtr->sendSMS(sms); } int main(int argc, char *argv[]) { if(argv[1]) { string input = argv[1]; string test = "--author"; if(input == test) { cout << "s149113" << endl; return 0; } } string line = ""; string file = "sms_out.txt"; ifstream myfile(file.c_str()); while(getline(myfile, line)) { string idnr, landcode, number, error; istringstream linestream(line); unsigned short errorcode; //Split the sentence getline(linestream, idnr, '\t'); getline(linestream, landcode, ':'); getline(linestream, number, '\t'); getline(linestream, error); if(idnr == "") break; //Make string to int try { errorcode = atoi(error.c_str() ); } catch (exception &) { } //Put together landcode and tlfnumber string nr = landcode + number; string txt = "Thank you for your vote!"; if(errorcode == 100) txt = "Invalid question, please try again"; else if(errorcode == 110) txt = "Sorry, only one vote pr. number"; else if(errorcode == 200) txt = "Invalid alternative, please try again"; else if(errorcode == 300) txt = "Missing a statement after other, please try again"; else if(errorcode == 999) txt = "An error occurred, please try again"; sms += "{\"ID\":" + idnr + ",\"nr\":" + nr + ",\"txt\":" + "\"" + txt + "\"" + "}\n"; } cout << sms << endl; sendSMS(sms); } //SMSDispatch.h #include <string> #ifndef SMSDISPATCH_H #define SMSDISPATCH_H using namespace std; class SMSDispatch{ public: virtual void sendSMS(string json); }; #endif //SMSDispatch.cpp #include <iostream> #include <fstream> #include "SMSDispatch.h" using namespace std; /*virtual*/void SMSDispatch::sendSMS(string json) { ofstream myfile; myfile.open ("sms_out.log"); myfile << json; myfile.close(); } int main() { }

    Read the article

  • error in assigning a const character to an unsigned char array in C++

    - by mekasperasky
    #include <iostream> #include <fstream> #include <cstring> using namespace std; typedef unsigned long int WORD; /* Should be 32-bit = 4 bytes */ #define w 32 /* word size in bits */ #define r 12 /* number of rounds */ #define b 16 /* number of bytes in key */ #define c 4 /* number words in key */ /* c = max(1,ceil(8*b/w)) */ #define t 26 /* size of table S = 2*(r+1) words */ WORD S [t],L[c]; /* expanded key table */ WORD P = 0xb7e15163, Q = 0x9e3779b9; /* magic constants */ /* Rotation operators. x must be unsigned, to get logical right shift*/ #define ROTL(x,y) (((x)<<(y&(w-1))) | ((x)>>(w-(y&(w-1))))) #define ROTR(x,y) (((x)>>(y&(w-1))) | ((x)<<(w-(y&(w-1))))) void RC5_DECRYPT(WORD *ct, WORD *pt) /* 2 WORD input ct/output pt */ { WORD i, B=ct[1], A=ct[0]; for (i=r; i>0; i--) { B = ROTR(B-S [2*i+1],A)^A; A = ROTR(A-S [2*i],B)^B; } pt [1] = B-S [1] ;pt [0] = A-S [0]; } void RC5_SETUP(unsigned char *K) /* secret input key K 0...b-1] */ { WORD i, j, k, u=w/8, A, B, L [c]; /* Initialize L, then S, then mix key into S */ for (i=b-1,L[c-1]=0; i!=-1; i--) L[i/u] = (L[i/u]<<8)+K[ i]; for (S [0]=P,i=1; i<t; i++) S [i] = S [i-1]+Q; for (A=B=i=j=k=0; k<3*t; k++,i=(i+1)%t,j=(j+1)%c) /* 3*t > 3*c */ { A = S[i] = ROTL(S [i]+(A+B),3); B = L[j] = ROTL(L[j]+(A+B),(A+B)); } } void printword(WORD A) { WORD k; for (k=0 ;k<w; k+=8) printf("%02.2lX",(A>>k)&0xFF); } int main() { WORD i, j, k, pt [2], pt2 [2], ct [2] = {0,0}; unsigned char key[b]; ofstream out("cpt.txt"); ifstream in("key.txt"); if(!in) { cout << "Cannot open file.\n"; return 1; } if(!out) { cout << "Cannot open file.\n"; return 1; } key="111111000001111"; RC5_SETUP(key); ct[0]=2185970173; ct[1]=3384368406; for (i=1;i<2;i++) { RC5_DECRYPT(ct,pt2); printf("\n plaintext "); printword(pt [0]); printword(pt[1]); } return 0; } When I compile this code, I get two warnings and also an error saying that I can't assign a char value to my character array. Why is that?

    Read the article

  • C++ function will not return

    - by Mike
    I have a function that I am calling that runs all the way up to where it should return but doesn't return. If I cout something for debugging at the very end of the function, it gets displayed but the function does not return. fetchData is the function I am referring to. It gets called by outputFile. cout displays "done here" but not "data fetched" I know this code is messy but can anyone help me figure this out? Thanks //Given an inode return all data of i_block data char* fetchData(iNode tempInode){ char* data; data = new char[tempInode.i_size]; this->currentInodeSize = tempInode.i_size; //Loop through blocks to retrieve data vector<unsigned int> i_blocks; i_blocks.reserve(tempInode.i_blocks); this->currentDataPosition = 0; cout << "currentDataPosition set to 0" << std::endl; cout << "i_blocks:" << tempInode.i_blocks << std::endl; int i = 0; for(i = 0; i < 12; i++){ if(tempInode.i_block[i] == 0) break; i_blocks.push_back(tempInode.i_block[i]); } appendIndirectData(tempInode.i_block[12], &i_blocks); appendDoubleIndirectData(tempInode.i_block[13], &i_blocks); appendTripleIndirectData(tempInode.i_block[14], &i_blocks); //Loop through all the block addresses to get the actual data for(i=0; i < i_blocks.size(); i++){ appendData(i_blocks[i], data); } cout << "done here" << std::endl; return data; } void appendData(int block, char* data){ char* tempBuffer; tempBuffer = new char[this->blockSize]; ifstream file (this->filename, std::ios::binary); int entryLocation = block*this->blockSize; file.seekg (entryLocation, ios::beg); file.read(tempBuffer, this->blockSize); //Append this block to data for(int i=0; i < this->blockSize; i++){ data[this->currentDataPosition] = tempBuffer[i]; this->currentDataPosition++; } data[this->currentDataPosition] = '\0'; } void outputFile(iNode file, string filename){ char* data; cout << "File Transfer Started" << std::endl; data = this->fetchData(file); cout << "data fetched" << std::endl; char *outputFile = (char*)filename.c_str(); ofstream myfile; myfile.open (outputFile,ios::out|ios::binary); int i = 0; for(i=0; i < file.i_size; i++){ myfile << data[i]; } myfile.close(); cout << "File Transfer Completed" << std::endl; return; }

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >