Search Results

Search found 106 results on 5 pages for 'istream'.

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

  • Distinguishing between failure and end of file in read loop

    - by celtschk
    The idiomatic loop to read from an istream is while (thestream >> value) { // do something with value } Now this loop has one problem: It will not distinguish if the loop terminated due to end of file, or due to an error. For example, take the following test program: #include <iostream> #include <sstream> void readbools(std::istream& is) { bool b; while (is >> b) { std::cout << (b ? "T" : "F"); } std::cout << " - " << is.good() << is.eof() << is.fail() << is.bad() << "\n"; } void testread(std::string s) { std::istringstream is(s); is >> std::boolalpha; readbools(is); } int main() { testread("true false"); testread("true false tr"); } The first call to testread contains two valid bools, and therefore is not an error. The second call ends with a third, incomplete bool, and therefore is an error. Nevertheless, the behaviour of both is the same. In the first case, reading the boolean value fails because there is none, while in the second case it fails because it is incomplete, and in both cases EOF is hit. Indeed, the program above outputs twice the same line: TF - 0110 TF - 0110 To solve this problem, I thought of the following solution: while (thestream >> std::ws && !thestream.eof() && thestream >> value) { // do something with value } The idea is to detect regular EOF before actually trying to extract the value. Because there might be whitespace at the end of the file (which would not be an error, but cause read of the last item to not hit EOF), I first discard any whitespace (which cannot fail) and then test for EOF. Only if I'm not at the end of file, I try to read the value. For my example program, it indeed seems to work, and I get TF - 0100 TF - 0110 So in the first case (correct input), fail() returns false. Now my question: Is this solution guaranteed to work, or was I just (un-)lucky that it happened to give the desired result? Also: Is there a simpler (or, if my solution is wrong, a correct) way to get the desired result?

    Read the article

  • How to read arbitrary number of values using std::copy?

    - by Miro Kropacek
    Hi, I'm trying to code opposite action to this: std::ostream outs; // properly initialized of course std::set<int> my_set; // ditto outs << my_set.size(); std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) ); it should be something like this: std::istream ins; std::set<int>::size_type size; ins >> size; std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) ); But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source... Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)

    Read the article

  • Does a wrapper class for a COM interop IStream already exist?

    - by AnthonyWJones
    I'm about to write a Wrapper for a COM interop IStream so that code that expects a standard .NET Stream can use it. However it occurs to me that this sort of thing may already have been done before (although I haven't been able to find it myself with web searching). So I'm just putting this out here in case I'm about to re-invent the wheel. Note I've come across code implementing IStream wrapping a .NET stream but I need the reverse.

    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

  • C++: ifstream::getline problem

    - by Jay
    I am reading a file like this: char string[256]; std::ifstream file( "file.txt" ); // open the level file. if ( ! file ) // check if the file loaded fine. { // error } while ( file.getline( string, 256, ' ' ) ) { // handle input } Just for testing purposes, my file is just one line, with a space at the end: 12345 My code first reads the 12345 successfully. But then instead of the loop ending, it reads another string, which seems to be a return/newline. I have saved my file both in gedit and in nano. And I have also outputted it with the Linux cat command, and there is no return on the end. So the file should be fine. Why is my code reading a return/newline? Thanks.

    Read the article

  • Why can't I construct an std::istream_iterator with an unnamed temporary?

    - by Stumped6789
    g++ allows this construction of an istream_iterator from an ifstream instance: std::ifstream ifstr("test.txt"); std::istream_iterator<std::string> iter1(ifstr); ...but it doesn't allow the same construction with an unnamed temporary: std::istream_iterator<std::string> iter2(std::ifstream("test.txt")); This gives: error: no matching function for call to ‘std::istream_iterator, ptrdiff_t::istream_iterator(std::ifstream)’ Does anyone know why this doesn't work? - thanks!

    Read the article

  • Cocoa NSStream TCP connection to FTP

    - by Chuck
    Hi, I'm new to Cocoa, but not to programming. Recently I decided I wanted to write a FTP client for Mac, and so I first made it in the language I'm most comfortable in (on Windows), and then moved on to Cocoa when I had the workings of FTP communications down. My question is (apparently) a bit controversial: How do I establish a read/writeable connection to (a ftp server)? What I have so far (non working obviously): NSInputStream *iStream; NSOutputStream *oStream; NSHost *host = [NSHost hostWithAddress:@"127.0.0.1"]; [NSStream getStreamsToHost:host port:3333 inputStream:&iStream outputStream:&oStream]; // ftp port: 3333 [iStream retain]; [oStream retain]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream setDelegate:self]; [oStream setDelegate:self]; // which is not implemented apparently [iStream open]; [oStream open]; // .... [iStream write: (const uint8_t *)buf maxLength:8]; Which is partially based on http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/Streams/Articles/NetworkStreams.html Now, why have I chosen NSStream? Because while this question is merely about how to connect to a FTP stream, my whole project will also include SSL and as far as I've been able to search here and on google, NSStream is capable of "switching" to a SSL connection. I've not been able to see the connection being made (which I'm usually able to do), but I also heard something about having to write to the stream before the stream will open? Any pointers are greatly appreciated, and sorry if my question is annoying - I'm new to Cocoa :)

    Read the article

  • Cocoa Read NSInputStream from FTP connection

    - by Chuck
    Hi, I (apparently) manage to make a ftp connection, but fail to read anything from it, and with good cause: I don't reach the reading until the connection has timed out. Here's my code: NSHost *host = [NSHost hostWithAddress:@"127.0.0.1"]; [NSStream getStreamsToHost:host port:3333 inputStream:&iStream outputStream:&oStream]; NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:1]; [settings setObject:(NSString *)NSStreamSocketSecurityLevelTLSv1 forKey:(NSString *)kCFStreamSSLLevel]; [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFReadStreamSetProperty((CFReadStreamRef)iStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);forKey:NSStreamSocketSecurityLevelKey]; [iStream open]; [oStream retain]; [oStream setDelegate:self]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFWriteStreamSetProperty((CFWriteStreamRef)oStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings); forKey:NSStreamSocketSecurityLevelKey]; [oStream open]; NSMutableData *returnMessage = [NSMutableData dataWithLength: 300]; [iStream read: [returnMessage mutableBytes] maxLength: 300]; NSString *readData = [[NSString alloc] initWithBytes: [returnMessage bytes] length: 300 encoding: NSUTF8StringEncoding]; NSRunAlertPanel(@"response", readData, nil, nil, nil); I have not sent a request to the FTP to switch to ssl yet. Any help is greatly appreciated as I find Xcode quite horrible for debugging (no exception or error msg on failed steps what so ever). Chuck

    Read the article

  • Cannot run java as regular linux user.

    - by Roger
    I am having problems trying to run java as a normal user on linux. It runs fine as root user but not as a regular user. Any help would be apreciated. Thanks root@pro1 [~]# which java /usr/local/jdk/bin/java root@pro1 [~]# java -version java version "1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03, mixed mode) root@pro1 [~]# su istream istream@xxxxxxxxx [/root]# which java /usr/local/jdk/bin/java istream@xxxxxxxxx [/root]# java -version Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. istream@xxxxxxxxx [/root]#

    Read the article

  • NSStream sockets missing data

    - by Chris T.
    I am trying to pull some sample data from FreeDB as a proof of concept, but I am having a tough time retrieving all of the data off the incoming stream (I am only getting the last bits for the final query listed here (if handshakeCode = 3) I think this may be something with the threading on the main runloop, but I am not sure. Odd thing is when the buffer size is larger than 1-2 bytes (which works as expected), I seem to be losing access to the data programmatically (the totalOutput variable on the first set of data is incomplete). I set up a packet capture, and it looks like those 1024 bytes are coming across the wire, but the app just isn't working with it. It looks like the next event is coming through and basically taking over. I tried using an NSLock to no avail as well. If I drop the buffer size down to 1 or 2, things seem to be reading just fine. This is probably obvious to someone who does this all the time, but this is my first foray into this with something I am familiar with, technology wise in other languages / platforms. The following code will show you what is happening. Run with the buffer set to 1024, and you will see a short final string, but once you set it to 1, you will see the amount of data I was expecting (I was even expecting it to be split, so that's not a big worry) #import <Foundation/Foundation.h> #import <Cocoa/Cocoa.h> //STACK OVERFLOW CODE: @interface stackoverflow : NSObject <NSStreamDelegate> { NSInputStream *iStream; NSOutputStream *oStream; int handshakeCode; NSString *selectedDiscId; NSString *selectedGenre; } -(void)getMatchesFromFreeDB; -(void)sendToOutputStream:(NSString*)command; @end @implementation stackoverflow -(void)getMatchesFromFreeDB { NSHost *host = [NSHost hostWithName:@"freedb.freedb.org"]; [NSStream getStreamsToHost:host port:8880 inputStream:&iStream outputStream:&oStream]; [iStream retain]; [oStream retain]; [iStream setDelegate:self]; [oStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream open]; [oStream open]; handshakeCode = 0; //not done any processing } -(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch(eventCode) { case NSStreamEventOpenCompleted: { NSLog(@"Stream open completed"); break; } case NSStreamEventHasBytesAvailable: { NSLog(@"Stream has bytes available"); if (aStream == iStream) { NSMutableString *totalOutput = [NSMutableString stringWithString:@""]; //read data uint8_t buffer[1024]; int len; while ([iStream hasBytesAvailable]) { len = [iStream read:buffer maxLength:sizeof(buffer)]; if (len 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; //this could have also been put into an NSData object if (nil != output) { //append to the total output [totalOutput appendString:output]; } } } NSLog(@"OUTPUT , %i:\n\n%@", [totalOutput lengthOfBytesUsingEncoding:NSUTF8StringEncoding], totalOutput); NSArray *outputComponents = [totalOutput componentsSeparatedByString:@" "]; //Attempt to get handshake code, since we haven't done it yet: if (handshakeCode == 1) { //we are just getting the sign-on banner: //let's move on: handshakeCode = 2; } else if (handshakeCode == 2) { handshakeCode = [[outputComponents objectAtIndex:0] intValue]; if (handshakeCode == 200) { NSLog(@"---Handshake OK %i", handshakeCode); NSMutableString *query = [NSMutableString stringWithString:@"cddb query f3114b11 17 225 19915 36489 54850 69425 87025 103948 123242 136075 152817 178335 192850 211677 235104 262090 284882 308658 4430\n"]; handshakeCode = 3; [self sendToOutputStream:query]; } } else if (handshakeCode == 3) { //now, we are reading out the matches: if ([[outputComponents objectAtIndex:0] intValue] == 200) //found exact match: { NSLog(@"Found exact match"); selectedGenre = [outputComponents objectAtIndex:1] ; selectedDiscId = [outputComponents objectAtIndex:2]; if (selectedGenre && selectedDiscId) { //send off the request to get the entry: NSString *query = [NSString stringWithFormat:@"cddb read %@ %@\n", selectedGenre, selectedDiscId]; [self sendToOutputStream:query]; handshakeCode = 4; } } } } break; } case NSStreamEventEndEncountered: { NSLog(@"Stream event end encountered"); break; } case NSStreamEventErrorOccurred: { NSLog(@"Stream error occurred"); break; } case NSStreamEventHasSpaceAvailable: { NSLog(@"Stream has space available"); if (aStream == oStream) { if (handshakeCode == 0) { handshakeCode = 1; [self sendToOutputStream:@"cddb hello stackoverflow localhost.localdomain test .01BETA\n"]; } } break; } } } -(void)sendToOutputStream:(NSString*)command { const uint8_t *rawCommand = (const uint8_t *)[command UTF8String]; [oStream write:rawCommand maxLength:strlen(rawCommand)]; NSLog(@"Sent command: %@",command); } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; stackoverflow *test = [[stackoverflow alloc] init]; [test getMatchesFromFreeDB]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop run]; [pool drain]; return 0; } Any help is much appreciated! Thanks

    Read the article

  • Program crash on deque from queue

    - by SwedishGit
    My first question asked here, so please excuse if I fail to include something... I'm working on a homework project, which basically consists of creating a "Jukebox" (importing/exporting albums from txt files, creating and "playing" a playlist, etc.). I've become stuck on one point: When "playing" the playlist, which consists of a self-made Queue, a copy of it is made from which songs are dequeued and printed out with a time delay. This appears to run fine on the first run through the program, but if the "play" option is chosen again (with the same playlist, created from a different menu option), it crashes before managing to print the first song. It also crashes if creating a new playlist, but then it manages to print some songs (seem to depend on the number of songs in the first/new playlists...) before crashing. With printouts I've been able to track the crashing down to being on the "item = n-data" call in the deque function... but can't get my head around why this would crash. Below is the code I think should be relevant... let me know if there are other parts that would help if I include. Edit: The Debug Error shown on crash is: R6010 abort() has been called The method to play from the playlist: void Jukebox::playList() { if(songList.getNodes() > 0) { Queue tmpList(songList); Song tmpSong; while(tmpList.deque(tmpSong)) { clock_t temp; temp = clock () + 2 * CLOCKS_PER_SEC ; while (clock() < temp) {} } } else cout << "There are no songs in the playlist!" << endl; } Queue: // Queue.h - Projekt-uppgift // Håkan Sjölin 2014-05-31 //----------------------------------------------------------------------------- #ifndef queue_h #define queue_h #include "Song.h" using namespace std; typedef Song Item; class Node; class Queue { private: Node *first; Node *last; int nodes; public: Queue():first(nullptr),last(nullptr),nodes(0){}; ~Queue(); void enque(Item item); bool deque(Item &item); int getNodes() const { return nodes; } void empty(); }; #endif // Queue.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-31 //----------------------------------------------------------------------------- #include "queue.h" using namespace std; class Node { public: Node *next; Item data; Node (Node *n, Item newData) : next(n), data(newData) {} }; //------------------------------------------------------------------------------ // Funktionsdefinitioner för klassen Queue //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Destruktor //------------------------------------------------------------------------------ Queue::~Queue() { while(first!=0) { Node *tmp = first; first = first->next; delete tmp; } } //------------------------------------------------------------------------------ // Lägg till data sist i kön //------------------------------------------------------------------------------ void Queue::enque(Item item) { Node *pNew = new Node(0,item); if(getNodes() < 1) first = pNew; else last->next = pNew; last = pNew; nodes++; } //------------------------------------------------------------------------------ // Ta bort data först i kön //------------------------------------------------------------------------------ bool Queue::deque(Item &item) { if(getNodes() < 1) return false; //cout << "deque: test2" << endl; Node *n = first; //cout << "deque: test3" << endl; //cout << "item = " << item << endl; //cout << "first = " << first << endl; //cout << "n->data = " << n->data << endl; item = n->data; //cout << "deque: test4" << endl; first = first->next; //delete n; nodes--; if(getNodes() < 1) // Kön BLEV tom last = nullptr; return true; } //------------------------------------------------------------------------------ // Töm kön //------------------------------------------------------------------------------ void Queue::empty() { while (getNodes() > 0) { Item item; deque(item); } } //------------------------------------------------------------------------------ Song: // Song.h - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #ifndef song_h #define song_h #include "Time.h" #include <string> #include <iostream> using namespace std; class Song { private: string title; string artist; Time length; public: Song(); Song(string pTitle, string pArtist, Time pLength); // Setfunktioner void setTitle(string pTitle); void setArtist(string pArtist); void setLength(Time pLength); // Getfunktioner string getTitle() const { return title;} string getArtist() const { return artist;} Time getLength() const { return length;} }; ostream &operator<<(ostream &os, const Song &song); istream &operator>>(istream &is, Song &song); #endif // Song.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #include "Song.h" #include "Constants.h" #include <iostream> //------------------------------------------------------------------------------ // Definiering av Songs medlemsfunktioner //------------------------------------------------------------------------------ // Fövald konstruktor //------------------------------------------------------------------------------ Song::Song() { } //------------------------------------------------------------------------------ // Initieringskonstruktor //------------------------------------------------------------------------------ Song::Song(string pTitle, string pArtist, Time pLength) { title = pTitle; artist = pArtist; length = pLength; } //------------------------------------------------------------------------------ // Setfunktioner //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // setTitle // Ange titel //------------------------------------------------------------------------------ void Song::setTitle(string pTitle) { title = pTitle; } //------------------------------------------------------------------------------ // setArtist // Ange artist //------------------------------------------------------------------------------ void Song::setArtist(string pArtist) { artist = pArtist; } //------------------------------------------------------------------------------ // setTitle // Ange titel //------------------------------------------------------------------------------ void Song::setLength(Time pLength) { length = pLength; } //--------------------------------------------------------------------------- // Överlagring av utskriftsoperatorn //--------------------------------------------------------------------------- ostream &operator<<(ostream &os, const Song &song) { os << song.getTitle() << DELIM << song.getArtist() << DELIM << song.getLength(); return os; } //--------------------------------------------------------------------------- // Överlagring av inmatningsoperatorn //--------------------------------------------------------------------------- istream &operator>>(istream &is, Song &song) { string tmpString; Time tmpLength; getline(is, tmpString, DELIM); song.setTitle(tmpString); getline(is, tmpString, DELIM); song.setArtist(tmpString); is >> tmpLength; is.get(); song.setLength(tmpLength); return is; } //--------------------------------------------------------------------------- Album: // Album.h - Projekt-uppgift // Håkan Sjölin 2014-05-17 //----------------------------------------------------------------------------- #ifndef album_h #define album_h #include "Song.h" #include <string> #include <vector> #include <iostream> using namespace std; class Album { private: string name; vector<Song> songs; public: Album(); Album(string pNameTitle, vector<Song> pSongs); // Setfunktioner void setName(string pName); // Getfunktioner string getName() const { return name;} vector<Song> getSongs() const { return songs;} int getNumberOfSongs() const { return songs.size();} Time getTotalTime() const; void addSong(Song pSong); bool operator<(const Album &album) const; }; ostream &operator<<(ostream &os, const Album &album); istream &operator>>(istream &is, Album &album); #endif // Album.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-17 //----------------------------------------------------------------------------- #include "Album.h" #include "Constants.h" #include <iostream> #include <string> //------------------------------------------------------------------------------ // Definiering av Albums medlemsfunktioner //------------------------------------------------------------------------------ // Fövald konstruktor //------------------------------------------------------------------------------ Album::Album() { } //------------------------------------------------------------------------------ // Initieringskonstruktor //------------------------------------------------------------------------------ Album::Album(string pName, vector<Song> pSongs) { name = pName; songs = pSongs; } //------------------------------------------------------------------------------ // Setfunktioner //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // setName // Ange namn //------------------------------------------------------------------------------ void Album::setName(string pName) { name = pName; } //------------------------------------------------------------------------------ // addSong // Lägg till song //------------------------------------------------------------------------------ void Album::addSong(Song pSong) { songs.push_back(pSong); } //------------------------------------------------------------------------------ // getTotalTime // Returnera total speltid //------------------------------------------------------------------------------ Time Album::getTotalTime() const { Time tTime(0,0,0); for(Song s : songs) { tTime = tTime + s.getLength(); } return tTime; } //--------------------------------------------------------------------------- // Mindre än //--------------------------------------------------------------------------- bool Album::operator<(const Album &album) const { return getTotalTime() < album.getTotalTime(); } //--------------------------------------------------------------------------- // Överlagring av utskriftsoperatorn //--------------------------------------------------------------------------- ostream &operator<<(ostream &os, const Album &album) { os << album.getName() << endl; os << album.getNumberOfSongs() << endl; for (size_t i = 0; i < album.getSongs().size(); i++) os << album.getSongs().at(i) << endl; return os; } //--------------------------------------------------------------------------- // Överlagring av inmatningsoperatorn //--------------------------------------------------------------------------- istream &operator>>(istream &is, Album &album) { string tmpString; int tmpNumberOfSongs; Song tmpSong; getline(is, tmpString); album.setName(tmpString); is >> tmpNumberOfSongs; is.get(); for (int i = 0; i < tmpNumberOfSongs; i++) { is >> tmpSong; album.addSong(tmpSong); } return is; } //--------------------------------------------------------------------------- Time: // Time.h - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #ifndef time_h #define time_h #include <iostream> using namespace std; class Time { private: int hours; int minutes; int seconds; public: Time(); Time(int pHour, int pMinute, int pSecond); // Setfunktioner void setHour(int pHour); void setMinute(int pMinute); void setSecond(int pSecond); // Getfunktioner int getHour() const { return hours;} int getMinute() const { return minutes;} int getSecond() const { return seconds;} Time operator+(const Time &time) const; bool operator==(const Time &time) const; bool operator<(const Time &time) const; }; ostream &operator<<(ostream &os, const Time &time); istream &operator>>(istream &is, Time &Time); #endif // Time.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #include "Time.h" #include <iostream> //------------------------------------------------------------------------------ // Definiering av Times medlemsfunktioner //------------------------------------------------------------------------------ // Fövald konstruktor //------------------------------------------------------------------------------ Time::Time() { } //------------------------------------------------------------------------------ // Initieringskonstruktor //------------------------------------------------------------------------------ Time::Time(int pHour, int pMinute, int pSecond) { setHour(pHour); setMinute(pMinute); setSecond(pSecond); } //------------------------------------------------------------------------------ // Setfunktioner //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // setHour // Ange timme //------------------------------------------------------------------------------ void Time::setHour(int pHour) { if(pHour>-1) hours = pHour; else hours = 0; } //------------------------------------------------------------------------------ // setMinute // Ange minut //------------------------------------------------------------------------------ void Time::setMinute(int pMinute) { if(pMinute < 60 && pMinute > -1) { minutes = pMinute; } else minutes = 0; } //------------------------------------------------------------------------------ // setSecond // Ange sekund //------------------------------------------------------------------------------ void Time::setSecond(int pSecond) { if(pSecond < 60 && pSecond > -1) { seconds = pSecond; } else seconds = 0; } //--------------------------------------------------------------------------- // Överlagring av utskriftsoperatorn //--------------------------------------------------------------------------- ostream &operator<<(ostream &os, const Time &time) { os << time.getHour()*3600+time.getMinute()*60+time.getSecond(); return os; } //--------------------------------------------------------------------------- // Överlagring av inmatningsoperatorn //--------------------------------------------------------------------------- istream &operator>>(istream &is, Time &time) { int tmp; is >> tmp; time.setSecond(tmp%60); time.setMinute((tmp/60)%60); time.setHour(tmp/3600); return is; } //--------------------------------------------------------------------------- // Likhet //-------------------------------------------------------------------------- bool Time::operator==(const Time &time) const { return hours == time.getHour() && minutes == time.getMinute() && seconds == time.getSecond(); } //--------------------------------------------------------------------------- // Mindre än //--------------------------------------------------------------------------- bool Time::operator<(const Time &time) const { if(hours == time.getHour()) { if(minutes == time.getMinute()) { return seconds < time.getSecond(); } else { return minutes < time.getMinute(); } } else { return hours < time.getHour(); } } //--------------------------------------------------------------------------- // Addition //--------------------------------------------------------------------------- Time Time::operator+(const Time &time) const { return Time(hours+time.getHour() + (minutes+time.getMinute() + (seconds+time.getSecond())/60)/60, (minutes+time.getMinute() + (seconds+time.getSecond())/60)%60, (seconds+time.getSecond())%60); } //--------------------------------------------------------------------------- Thanks in advance for any help! Edit2: Didn't think of including the more detailed crash info (as it didn't show in the crash pop-up, so to say). Anyway, here it is: Output: 'Jukebox.exe' (Win32): Loaded 'C:\Users\Håkan\Documents\Studier - IT\Objektbaserad programmering i C++\Inlämningsuppgifter\Projekt\Jukebox\Debug\Jukebox.exe'. Symbols loaded. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp110d.dll'. Symbols loaded. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr110d.dll'. Symbols loaded. The thread 0xe50 has exited with code 0 (0x0). Unhandled exception at 0x0083630C in Jukebox.exe: 0xC0000005: Access violation reading location 0x0000003C. Call stack: > Jukebox.exe!Song::getLength() Line 27 C++ Jukebox.exe!operator<<(std::basic_ostream<char,std::char_traits<char> > & os, const Song & song) Line 59 C++ Jukebox.exe!Queue::deque(Song & item) Line 55 C++ Jukebox.exe!Jukebox::playList() Line 493 C++ Jukebox.exe!Jukebox::play() Line 385 C++ Jukebox.exe!Jukebox::run() Line 536 C++ Jukebox.exe!main() Line 547 C++ Jukebox.exe!__tmainCRTStartup() Line 536 C Jukebox.exe!mainCRTStartup() Line 377 C kernel32.dll!754d86e3() Unknown [Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll] ntdll.dll!7748bf39() Unknown ntdll.dll!7748bf0c() Unknown

    Read the article

  • Can IMAPI2 burn files with the size > 4Gb?

    - by Sergey Skoblikov
    IMAPI2 interface IFileSystem uses COM IStream interfaces to represent file data. There is AddTree method that adds specified directory contents to IFileSystem. So AddTree must create IStream's in the process. I wonder what implementation of IStream it uses? If it uses the standard OLE implementation than we have a nasty problem because OLE streams doesn't support files bigger than 4Gb. Can anyone shed some light on this issue?

    Read the article

  • Large File Download - Connection With Server Reset

    - by daveywc
    I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset. Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event. private void DownloadFile(string fname, bool forceDownload) { string path = MapPath(fname); string name = Path.GetFileName(path); string ext = Path.GetExtension(path); string type = ""; // set known types based on file extension if (ext != null) { switch (ext.ToLower()) { case ".mp3": type = "audio/mpeg"; break; case ".htm": case ".html": type = "text/HTML"; break; case ".txt": type = "text/plain"; break; case ".doc": case ".rtf": type = "Application/msword"; break; } } if (forceDownload) { Response.AppendHeader("content-disposition", "attachment; filename=" + name.Replace(" ", "_")); } if (type != "") { Response.ContentType = type; } else { Response.ContentType = "application/x-msdownload"; } System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } }

    Read the article

  • How can I create a Base64-Encoded string from an GDI+ Image in C++?

    - by Schnapple
    I asked a question recently, How can I create an Image in GDI+ from a Base64-Encoded string in C++?, which got a response that led me to the answer. Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward. The crux of the issue is that an Image in GDI+ can save out its data to either a file or an IStream*. I don't want to save to a file, so I need to use the resulting stream. Problem is, this is where my knowledge breaks down. This first part is what I figured out in the other question // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); // I have this decode function from elsewhere std::string decodedImage = base64_decode(Base64EncodedImage); // Allocate the space for the stream DWORD imageSize = decodedImage.length(); HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize); LPVOID pImage = ::GlobalLock(hMem); memcpy(pImage, decodedImage.c_str(), imageSize); // Create the stream IStream* pStream = NULL; ::CreateStreamOnHGlobal(hMem, FALSE, &pStream); // Create the image from the stream Image image(pStream); // Cleanup pStream->Release(); GlobalUnlock(hMem); GlobalFree(hMem); (Base64 code) And now I'm going to perform an operation on the resulting image, in this case rotating it, and now I want the Base64-equivalent string when I'm done. // Perform operation (rotate) image.RotateFlip(Gdiplus::Rotate180FlipNone); IStream* oStream = NULL; CLSID tiffClsid; GetEncoderClsid(L"image/tiff", &tiffClsid); // Function defined elsewhere image.Save(oStream, &tiffClsid); // And here's where I'm stumped. (GetEncoderClsid) So what I wind up with at the end is an IStream* object. But here's where both my knowledge and Google break down for me. IStream shouldn't be an object itself, it's an interface for other types of streams. I'd go down the road from getting string-Image in reverse, but I don't know how to determine the size of the stream, which appears to be key to that route. How can I go from an IStream* to a string (which I will then Base64-Encode)? Or is there a much better way to go from a GDI+ Image to a string?

    Read the article

  • Beginner question about getting reference to cin

    - by John C
    I'm having problems wrapping my head around this. I have a function void foo(istream& input) { input = cin; } This fails (I'm assuming because cin isn't supposed to be "copyable". however, this works void foo(istream& input) { istream& baz = cin; } Is there a reason that I can get a reference to cin in baz but I cannot assign it to input? Thanks

    Read the article

  • Accelerated C++, problem 5-6 (copying values from inside a vector to the front)

    - by Darel
    Hello, I'm working through the exercises in Accelerated C++ and I'm stuck on question 5-6. Here's the problem description: (somewhat abbreviated, I've removed extraneous info.) 5-6. Write the extract_fails function so that it copies the records for the passing students to the beginning of students, and then uses the resize function to remove the extra elements from the end of students. (students is a vector of student structures. student structures contain an individual student's name and grades.) More specifically, I'm having trouble getting the vector.insert function to properly copy the passing student structures to the start of the vector students. Here's the extract_fails function as I have it so far (note it doesn't resize the vector yet, as directed by the problem description; that should be trivial once I get past my current issue.) // Extract the students who failed from the "students" vector. void extract_fails(vector<Student_info>& students) { typedef vector<Student_info>::size_type str_sz; typedef vector<Student_info>::iterator iter; iter it = students.begin(); str_sz i = 0, count = 0; while (it != students.end()) { // fgrade tests wether or not the student failed if (!fgrade(*it)) { // if student passed, copy to front of vector students.insert(students.begin(), it, it); // tracks of the number of passing students(so we can properly resize the array) count++; } cout << it->name << endl; // output to verify that each student is iterated to it++; } } The code compiles and runs, but the students vector isn't adding any student structures to its front. My program's output displays that the students vector is unchanged. Here's my complete source code, followed by a sample input file (I redirect input from the console by typing " < grades" after the compiled program name at the command prompt.) #include <iostream> #include <string> #include <algorithm> // to get the declaration of `sort' #include <stdexcept> // to get the declaration of `domain_error' #include <vector> // to get the declaration of `vector' //driver program for grade partitioning examples using std::cin; using std::cout; using std::endl; using std::string; using std::domain_error; using std::sort; using std::vector; using std::max; using std::istream; struct Student_info { std::string name; double midterm, final; std::vector<double> homework; }; bool compare(const Student_info&, const Student_info&); std::istream& read(std::istream&, Student_info&); std::istream& read_hw(std::istream&, std::vector<double>&); double median(std::vector<double>); double grade(double, double, double); double grade(double, double, const std::vector<double>&); double grade(const Student_info&); bool fgrade(const Student_info&); void extract_fails(vector<Student_info>& v); int main() { vector<Student_info> vs; Student_info s; string::size_type maxlen = 0; while (read(cin, s)) { maxlen = max(maxlen, s.name.size()); vs.push_back(s); } sort(vs.begin(), vs.end(), compare); extract_fails(vs); // display the new, modified vector - it should be larger than // the input vector, due to some student structures being // added to the front of the vector. cout << "count: " << vs.size() << endl << endl; vector<Student_info>::iterator it = vs.begin(); while (it != vs.end()) cout << it++->name << endl; return 0; } // Extract the students who failed from the "students" vector. void extract_fails(vector<Student_info>& students) { typedef vector<Student_info>::size_type str_sz; typedef vector<Student_info>::iterator iter; iter it = students.begin(); str_sz i = 0, count = 0; while (it != students.end()) { // fgrade tests wether or not the student failed if (!fgrade(*it)) { // if student passed, copy to front of vector students.insert(students.begin(), it, it); // tracks of the number of passing students(so we can properly resize the array) count++; } cout << it->name << endl; // output to verify that each student is iterated to it++; } } bool compare(const Student_info& x, const Student_info& y) { return x.name < y.name; } istream& read(istream& is, Student_info& s) { // read and store the student's name and midterm and final exam grades is >> s.name >> s.midterm >> s.final; read_hw(is, s.homework); // read and store all the student's homework grades return is; } // read homework grades from an input stream into a `vector<double>' istream& read_hw(istream& in, vector<double>& hw) { if (in) { // get rid of previous contents hw.clear(); // read homework grades double x; while (in >> x) hw.push_back(x); // clear the stream so that input will work for the next student in.clear(); } return in; } // compute the median of a `vector<double>' // note that calling this function copies the entire argument `vector' double median(vector<double> vec) { typedef vector<double>::size_type vec_sz; vec_sz size = vec.size(); if (size == 0) throw domain_error("median of an empty vector"); sort(vec.begin(), vec.end()); vec_sz mid = size/2; return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid]; } // compute a student's overall grade from midterm and final exam grades and homework grade double grade(double midterm, double final, double homework) { return 0.2 * midterm + 0.4 * final + 0.4 * homework; } // compute a student's overall grade from midterm and final exam grades // and vector of homework grades. // this function does not copy its argument, because `median' does so for us. double grade(double midterm, double final, const vector<double>& hw) { if (hw.size() == 0) throw domain_error("student has done no homework"); return grade(midterm, final, median(hw)); } double grade(const Student_info& s) { return grade(s.midterm, s.final, s.homework); } // predicate to determine whether a student failed bool fgrade(const Student_info& s) { return grade(s) < 60; } Sample input file: Moo 100 100 100 100 100 100 100 100 Fail1 45 55 65 80 90 70 65 60 Moore 75 85 77 59 0 85 75 89 Norman 57 78 73 66 78 70 88 89 Olson 89 86 70 90 55 73 80 84 Peerson 47 70 82 73 50 87 73 71 Baker 67 72 73 40 0 78 55 70 Davis 77 70 82 65 70 77 83 81 Edwards 77 72 73 80 90 93 75 90 Fail2 55 55 65 50 55 60 65 60 Thanks to anyone who takes the time to look at this!

    Read the article

  • overloaded stream insertion operator with a vector

    - by Julz
    hi, i'm trying to write an overloaded stream insertion operator for a class who's only member is a vector. i dont really know what i'm doing. (lets make that clear) it's a vector of "Points" which is a struct containing two doubles. i figure what i want is to insert user input (a bunch of doubles) into a stream that i then send to a modifier method? i keep working off other stream insertion examples such as... std::ostream& operator<< (std::ostream& o, Fred const& fred) { return o << fred.i_; } but when i try a similar..... istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr.vertices; return inStream; } i get an error "no match for operator etc etc. if i leave off the .vertices it compiles but i figure it's not right? (vertices is the name of my vector ) and even if it is right, i dont actually know what syntax to use in my driver to use it? also not %100 on what my modifier method needs to look like. here's my Polygon class //header #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); public: //Constructor Polygon(const Point &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return (int) vertices.capacity();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; #endif //Body using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const Point &theVerts) { vertices.push_back (theVerts); } //Copy Constructor Polygon::Polygon(const Polygon &polyCopy) { vertices = polyCopy.vertices; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } any help greatly appreciated, sorry to be so vague, a lecturer has just kind of given us a brief example of stream insertion then left us on our own thanks. oh i realise there are probably many other problems that need fixing

    Read the article

  • overloaded stream insetion operator with a vector

    - by julz666
    hi, i'm trying to write an overloaded stream insertion operator for a class who's only member is a vector. i dont really know what i'm doing. (lets make that clear) it's a vector of "Points" which is a struct containing two doubles. i figure what i want is to insert user input (a bunch of doubles) into a stream that i then send to a modifier method? i keep working off other stream insertion examples such as... std::ostream& operator<< (std::ostream& o, Fred const& fred) { return o << fred.i_; } but when i try a similar..... istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr.vertices; return inStream; } i get an error "no match for operator etc etc. if i leave off the .vertices it compiles but i figure it's not right? (vertices is the name of my vector ) and even if it is right, i dont actually know what syntax to use in my driver to use it? also not %100 on what my modifier method needs to look like. here's my Polygon class //header #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); public: //Constructor Polygon(const Point &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return (int) vertices.capacity();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; #endif //Body using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const Point &theVerts) { vertices.push_back (theVerts); } //Copy Constructor Polygon::Polygon(const Polygon &polyCopy) { vertices = polyCopy.vertices; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } any help greatly appreciated, sorry to be so vague, a lecturer has just kind of given us a brief example of stream insertion then left us on our own thanks. oh i realise there are probably many other problems that need fixing

    Read the article

  • Problem compiling c++ in CodeGear

    - by Carlos
    I have written a C++ program for a University assignment. I used Netbeans 6.8 running on my Mac and the code runs smoothly, no warnings, errors or problems/bugs. However when compiling and running on a Windows computer using CodeGear RAD Studio 2009 (C++ Builder) am getting several errors. [BCC32 Error] main.cpp(51): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string' [BCC32 Error] main.cpp(62): E2093 'operator==' not implemented in type 'string' for arguments of the same type [BCC32 Error] main.cpp(67): E2093 'operator==' not implemented in type 'string' for arguments of the same type [BCC32 Error] main.cpp(112): E2093 'operator==' not implemented in type 'string' for arguments of the same type [BCC32 Error] main.cpp(121): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string' [BCC32 Error] main.cpp(130): E2093 'operator==' not implemented in type 'string' for arguments of the same type [BCC32 Error] main.cpp(133): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string' [BCC32 Error] main.cpp(139): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string' [BCC32 Error] main.cpp(153): E2094 'operator<<' not implemented in type 'fstream' for arguments of type 'string' [BCC32 Error] main.cpp(199): E2094 'operator>>' not implemented in type 'fstream' for arguments of type 'string' [BCC32 Error] main.cpp(219): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string' [BCC32 Error] main.cpp(231): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string' [BCC32 Error] main.cpp(240): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string' [BCC32 Error] main.cpp(262): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string' [BCC32 Error] main.cpp(264): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string' These are the header files am using #include <iostream> #include <fstream> #include <cmath> #include <stdio> #include <windows> //I added this one just to check and still does not work (I didnt have it on Netbeans/Mac) using namespace std; Any ideas what is producing the errors and how can I fix it?

    Read the article

  • Piping EOF problems with stdio and C++/Python

    - by yeus
    I got some problems with EOF and stdio. I have no idea what I am doing wrong. When I see an EOF in my program I clear the stdin and next round I try to read in a new line. The problem is: for some reason the getline function immediatly (from the second run always, the first works just as intended) returns an EOF instead of waiting for a new input from py python process... Any idea? alright Here is the code: #include <string> #include <iostream> #include <iomanip> #include <limits> using namespace std; int main(int argc, char **argv) { for (;;) { string buf; if (getline(cin,buf)) { if (buf=="q") break; /*****///do some stuff with input //my actual filter program cout<<buf; /*****/ } else { if ((cin.rdstate() & istream::eofbit)!=0)cout<<"eofbit"<<endl; if ((cin.rdstate() & istream::failbit)!=0)cout<<"failbit"<<endl; if ((cin.rdstate() & istream::badbit)!=0)cout<<"badbit"<<endl; if ((cin.rdstate() & istream::goodbit)!=0)cout<<"goodbit"<<endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max()); //break;//I am not using break, because I //want more input when the parent //process puts data into stdin; } } return 0; } and in python: from subprocess import Popen, PIPE import os from time import sleep proc=Popen(os.getcwd()+"/Pipingtest",stdout=PIPE,stdin=PIPE,stderr=PIPE); while(1): sleep(0.5) print proc.communicate("1 1 1") print "running"

    Read the article

  • updateBinaryStream on ResultSet with FileStream

    - by Lieven Cardoen
    If I try to update a FileStream column I get following error: com.microsoft.sqlserver.jdbc.SQLServerException: The result set is not updatable. Code: System.out.print("Now, let's update the filestream data."); FileInputStream iStream = new FileInputStream("c:\\testFile.mp3"); rs.updateBinaryStream(2, iStream, -1); rs.updateRow(); iStream.close(); Why is this? Table in Sql Server 2008: CREATE TABLE [BinaryAssets].[BinaryAssetFiles]( [BinaryAssetFileId] [int] IDENTITY(1,1) NOT NULL, [FileStreamId] [uniqueidentifier] ROWGUIDCOL NOT NULL, [Blob] [varbinary](max) FILESTREAM NULL, [HashCode] [nvarchar](100) NOT NULL, [Size] [int] NOT NULL, [BinaryAssetExtensionId] [int] NOT NULL, Query used in Java: String strCmd = "select BinaryAssetFileId, Blob from BinaryAssets.BinaryAssetFiles where BinaryAssetFileId = 1"; stmt = con.createStatement(); rs = stmt.executeQuery(strCmd);

    Read the article

  • problem with NSInputStream on real iPhone

    - by ThamThang
    Hi guys, I have a problem with NSInputStream. Here is my code: case NSStreamEventHasBytesAvailable: printf("BYTE AVAILABLE\n"); int len = 0; NSMutableData *data = [[NSMutableData alloc] init]; uint8_t buffer[32768]; if(stream == iStream) { printf("Receiving...\n"); len = [iStream read:buffer maxLength:32768]; [data appendBytes:buffer length:len]; } [iStream close]; I try to read small data and it works perfectly on simulator and real iPhone. If I try to read large data (more than 4kB or maybe 5kB), the real iPhone just can read 2736 bytes and stop. Why is it? Help me plz! Merci d'avance!

    Read the article

  • how to cout a vector of structs (that's a class member, using extraction operator)

    - by Julz
    hi, i'm trying to simply cout the elements of a vector using an overloaded extraction operator. the vector contians Point, which is just a struct containing two doubles. the vector is a private member of a class called Polygon, so heres my Point.h #ifndef POINT_H #define POINT_H #include <iostream> #include <string> #include <sstream> struct Point { double x; double y; //constructor Point() { x = 0.0; y = 0.0; } friend std::istream& operator >>(std::istream& stream, Point &p) { stream >> std::ws; stream >> p.x; stream >> p.y; return stream; } friend std::ostream& operator << (std::ostream& stream, Point &p) { stream << p.x << p.y; return stream; } }; #endif my Polygon.h #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { //insertion operator needs work friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); // extraction operator friend std::ostream & operator << (std::ostream &outStream, const Polygon &vertStr); public: //Constructor Polygon(const std::vector<Point> &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return vertices.size();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; and Polygon.cc using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const vector<Point> &theVerts) { vertices = theVerts; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon::Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } // extraction operator ostream & operator << (ostream &outStream, const Polygon::Polygon &vertStr) { outStream << vertStr.vertices << endl; return outStream; } i figure my Point insertion/extraction is right, i can insert and cout using it and i figure i should be able to just...... cout << myPoly[i] << endl; in my driver? (in a loop) or even... cout << myPoly[0] << endl; without a loop? i've tried all sorts of myPoly.at[i]; myPoly.vertices[i]; etc etc also tried all veriations in my extraction function outStream << vertStr.vertices[i] << endl; within loops, etc etc. when i just create a... vector<Point> myVect; in my driver i can just... cout << myVect.at(i) << endl; no problems. tried to find an answer for days, really lost and not through lack of trying!!! thanks in advance for any help. please excuse my lack of comments and formatting also there's bits and pieces missing but i really just need an answer to this problem thanks again

    Read the article

  • Get result type of function

    - by Robert
    I want to specialize a template function declared as: template<typename Type> Type read(std::istream& is); I then have a lot of static implementations static int read_integer(std::istream& is); a.s.o. Now I'd like to do a macro so that specialization of read is as simple as: SPECIALIZE_READ(read_integer) So I figured I'd go the boost::function_traits way and declare SPECIALIZE_READ as: #define SPECIALIZE_READ(read_function) \ template<> boost::function_traits<read_function>::result_type read(std::istream& is) { \ return read_function(is); \ } but VC++ (2008) compiler complains with: 'boost::function_traits' : 'read_integer' is not a valid template type argument for parameter 'Function' Ideas ?

    Read the article

  • C++ - Implementing my own stream

    - by HardCoder1986
    Hello! My problem can be described the following way: I have some data which actually is an array and could be represented as char* data with some size I also have some legacy code (function) that takes some abstract std::istream object as a param and uses that stream to retrieve data to operate. So, my question is the following - what would be the easy way to map my data to some std::istream object so that I can pass it to my function? I thought about creating a std::stringstream object from my data, but that means copying and (as I assume) isn't the best solution. Any ideas how this could be done so that my std::istream operates on the data directly? Thank you.

    Read the article

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