Search Results

Search found 151 results on 7 pages for 'ostream'.

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

  • 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

  • Logging Into a site that uses Live.com authentication with C#

    - by Josh
    I've been trying to automate a log in to a website I frequent, www.bungie.net. The site is associated with Microsoft and Xbox Live, and as such makes uses of the Windows Live ID API when people log in to their site. I am relatively new to creating web spiders/robots, and I worry that I'm misunderstanding some of the most basic concepts. I've simulated logins to other sites such as Facebook and Gmail, but live.com has given me nothing but trouble. Anyways, I've been using Wireshark and the Firefox addon Tamper Data to try and figure out what I need to post, and what cookies I need to include with my requests. As far as I know these are the steps one must follow to log in to this site. 1. Visit https: //login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917 2. Recieve the cookies MSPRequ and MSPOK. 3. Post the values from the form ID "PPSX", the values from the form ID "PPFT", your username, your password all to a changing URL similar to: https: //login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct= (there are a few numbers that change at the end of that URL) 4. Live.com returns the user a page with more hidden forms to post. The client then posts the values from the form "ANON", the value from the form "ANONExp" and the values from the form "t" to the URL: http ://www.bung ie.net/Default.aspx?wa=wsignin1.0 5. After posting that data, the user is returned a variety of cookies the most important of which is "BNGAuth" which is the log in cookie for the site. Where I am having trouble is on fifth step, but that doesn't neccesarily mean I've done all the other steps correctly. I post the data from "ANON", "ANONExp" and "t" but instead of being returned a BNGAuth cookie, I'm returned a cookie named "RSPMaybe" and redirected to the home page. When I review the Wireshark log, I noticed something that instantly stood out to me as different between the log when I logged in with Firefox and when my program ran. It could be nothing but I'll include the picture here for you to review. I'm being returned an HTTP packet from the site before I post the data in the fourth step. I'm not sure how this is happening, but it must be a side effect from something I'm doing wrong in the HTTPS steps. ![alt text][1] http://img391.imageshack.us/img391/6049/31394881.gif using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Net; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Web; namespace SpiderFromScratch { class Program { static void Main(string[] args) { CookieContainer cookies = new CookieContainer(); Uri url = new Uri("https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"); HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(url); http.Timeout = 30000; http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.Referer = "http://www.bungie.net/"; http.ContentType = "application/x-www-form-urlencoded"; http.CookieContainer = new CookieContainer(); http.Method = WebRequestMethods.Http.Get; HttpWebResponse response = (HttpWebResponse)http.GetResponse(); StreamReader readStream = new StreamReader(response.GetResponseStream()); string HTML = readStream.ReadToEnd(); readStream.Close(); //gets the cookies (they are set in the eighth header) string[] strCookies = response.Headers.GetValues(8); response.Close(); string name, value; Cookie manualCookie; for (int i = 0; i < strCookies.Length; i++) { name = strCookies[i].Substring(0, strCookies[i].IndexOf("=")); value = strCookies[i].Substring(strCookies[i].IndexOf("=") + 1, strCookies[i].IndexOf(";") - strCookies[i].IndexOf("=") - 1); manualCookie = new Cookie(name, "\"" + value + "\""); Uri manualURL = new Uri("http://login.live.com"); http.CookieContainer.Add(manualURL, manualCookie); } //stores the cookies to be used later cookies = http.CookieContainer; //Get the PPSX value string PPSX = HTML.Remove(0, HTML.IndexOf("PPSX")); PPSX = PPSX.Remove(0, PPSX.IndexOf("value") + 7); PPSX = PPSX.Substring(0, PPSX.IndexOf("\"")); //Get this random PPFT value string PPFT = HTML.Remove(0, HTML.IndexOf("PPFT")); PPFT = PPFT.Remove(0, PPFT.IndexOf("value") + 7); PPFT = PPFT.Substring(0, PPFT.IndexOf("\"")); //Get the random URL you POST to string POSTURL = HTML.Remove(0, HTML.IndexOf("https://login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct=")); POSTURL = POSTURL.Substring(0, POSTURL.IndexOf("\"")); //POST with cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTURL); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.CookieContainer = cookies; http.Referer = "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268158321&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"; http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; Stream ostream = http.GetRequestStream(); //used to convert strings into bytes System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); //Post information byte[] buffer = encoding.GetBytes("PPSX=" + PPSX +"&PwdPad=IfYouAreReadingThisYouHaveTooMuc&login=YOUREMAILGOESHERE&passwd=YOURWORDGOESHERE" + "&LoginOptions=2&PPFT=" + PPFT); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); HttpWebResponse response2 = (HttpWebResponse)http.GetResponse(); readStream = new StreamReader(response2.GetResponseStream()); HTML = readStream.ReadToEnd(); response2.Close(); ostream.Dispose(); foreach (Cookie cookie in response2.Cookies) { Console.WriteLine(cookie.Name + ": "); Console.WriteLine(cookie.Value); Console.WriteLine(cookie.Expires); Console.WriteLine(); } //SET POSTURL value string POSTANON = "http://www.bungie.net/Default.aspx?wa=wsignin1.0"; //Get the ANON value string ANON = HTML.Remove(0, HTML.IndexOf("ANON")); ANON = ANON.Remove(0, ANON.IndexOf("value") + 7); ANON = ANON.Substring(0, ANON.IndexOf("\"")); ANON = HttpUtility.UrlEncode(ANON); //Get the ANONExp value string ANONExp = HTML.Remove(0, HTML.IndexOf("ANONExp")); ANONExp = ANONExp.Remove(0, ANONExp.IndexOf("value") + 7); ANONExp = ANONExp.Substring(0, ANONExp.IndexOf("\"")); ANONExp = HttpUtility.UrlEncode(ANONExp); //Get the t value string t = HTML.Remove(0, HTML.IndexOf("id=\"t\"")); t = t.Remove(0, t.IndexOf("value") + 7); t = t.Substring(0, t.IndexOf("\"")); t = HttpUtility.UrlEncode(t); //POST the Info and Accept the Bungie Cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTANON); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Encoding", "gzip,deflate"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "115"); http.CookieContainer = new CookieContainer(); http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; http.Expect = null; ostream = http.GetRequestStream(); int test = ANON.Length; int test1 = ANONExp.Length; int test2 = t.Length; buffer = encoding.GetBytes("ANON=" + ANON +"&ANONExp=" + ANONExp + "&t=" + t); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); //Here lies the problem, I am not returned the correct cookies. HttpWebResponse response3 = (HttpWebResponse)http.GetResponse(); GZipStream gzip = new GZipStream(response3.GetResponseStream(), CompressionMode.Decompress); readStream = new StreamReader(gzip); HTML = readStream.ReadToEnd(); //gets both cookies string[] strCookies2 = response3.Headers.GetValues(11); response3.Close(); } } } This has given me problems and I've put many hours into learning about HTTP protocols so any help would be appreciated. If there is an article detailing a similar log in to live.com feel free to point the way. I've been looking far and wide for any articles with working solutions. If I could be clearer, feel free to ask as this is my first time using Stack Overflow. Cheers, --Josh

    Read the article

  • Logging Into a site that uses Live.com authentication

    - by Josh
    I've been trying to automate a log in to a website I frequent, www.bungie.net. The site is associated with Microsoft and Xbox Live, and as such makes uses of the Windows Live ID API when people log in to their site. I am relatively new to creating web spiders/robots, and I worry that I'm misunderstanding some of the most basic concepts. I've simulated logins to other sites such as Facebook and Gmail, but live.com has given me nothing but trouble. Anyways, I've been using Wireshark and the Firefox addon Tamper Data to try and figure out what I need to post, and what cookies I need to include with my requests. As far as I know these are the steps one must follow to log in to this site. 1. Visit https: //login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917 2. Recieve the cookies MSPRequ and MSPOK. 3. Post the values from the form ID "PPSX", the values from the form ID "PPFT", your username, your password all to a changing URL similar to: https: //login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct= (there are a few numbers that change at the end of that URL) 4. Live.com returns the user a page with more hidden forms to post. The client then posts the values from the form "ANON", the value from the form "ANONExp" and the values from the form "t" to the URL: http ://www.bung ie.net/Default.aspx?wa=wsignin1.0 5. After posting that data, the user is returned a variety of cookies the most important of which is "BNGAuth" which is the log in cookie for the site. Where I am having trouble is on fifth step, but that doesn't neccesarily mean I've done all the other steps correctly. I post the data from "ANON", "ANONExp" and "t" but instead of being returned a BNGAuth cookie, I'm returned a cookie named "RSPMaybe" and redirected to the home page. When I review the Wireshark log, I noticed something that instantly stood out to me as different between the log when I logged in with Firefox and when my program ran. It could be nothing but I'll include the picture here for you to review. I'm being returned an HTTP packet from the site before I post the data in the fourth step. I'm not sure how this is happening, but it must be a side effect from something I'm doing wrong in the HTTPS steps. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Net; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Web; namespace SpiderFromScratch { class Program { static void Main(string[] args) { CookieContainer cookies = new CookieContainer(); Uri url = new Uri("https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"); HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(url); http.Timeout = 30000; http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.Referer = "http://www.bungie.net/"; http.ContentType = "application/x-www-form-urlencoded"; http.CookieContainer = new CookieContainer(); http.Method = WebRequestMethods.Http.Get; HttpWebResponse response = (HttpWebResponse)http.GetResponse(); StreamReader readStream = new StreamReader(response.GetResponseStream()); string HTML = readStream.ReadToEnd(); readStream.Close(); //gets the cookies (they are set in the eighth header) string[] strCookies = response.Headers.GetValues(8); response.Close(); string name, value; Cookie manualCookie; for (int i = 0; i < strCookies.Length; i++) { name = strCookies[i].Substring(0, strCookies[i].IndexOf("=")); value = strCookies[i].Substring(strCookies[i].IndexOf("=") + 1, strCookies[i].IndexOf(";") - strCookies[i].IndexOf("=") - 1); manualCookie = new Cookie(name, "\"" + value + "\""); Uri manualURL = new Uri("http://login.live.com"); http.CookieContainer.Add(manualURL, manualCookie); } //stores the cookies to be used later cookies = http.CookieContainer; //Get the PPSX value string PPSX = HTML.Remove(0, HTML.IndexOf("PPSX")); PPSX = PPSX.Remove(0, PPSX.IndexOf("value") + 7); PPSX = PPSX.Substring(0, PPSX.IndexOf("\"")); //Get this random PPFT value string PPFT = HTML.Remove(0, HTML.IndexOf("PPFT")); PPFT = PPFT.Remove(0, PPFT.IndexOf("value") + 7); PPFT = PPFT.Substring(0, PPFT.IndexOf("\"")); //Get the random URL you POST to string POSTURL = HTML.Remove(0, HTML.IndexOf("https://login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct=")); POSTURL = POSTURL.Substring(0, POSTURL.IndexOf("\"")); //POST with cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTURL); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.CookieContainer = cookies; http.Referer = "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268158321&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"; http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; Stream ostream = http.GetRequestStream(); //used to convert strings into bytes System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); //Post information byte[] buffer = encoding.GetBytes("PPSX=" + PPSX +"&PwdPad=IfYouAreReadingThisYouHaveTooMuc&login=YOUREMAILGOESHERE&passwd=YOURWORDGOESHERE" + "&LoginOptions=2&PPFT=" + PPFT); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); HttpWebResponse response2 = (HttpWebResponse)http.GetResponse(); readStream = new StreamReader(response2.GetResponseStream()); HTML = readStream.ReadToEnd(); response2.Close(); ostream.Dispose(); foreach (Cookie cookie in response2.Cookies) { Console.WriteLine(cookie.Name + ": "); Console.WriteLine(cookie.Value); Console.WriteLine(cookie.Expires); Console.WriteLine(); } //SET POSTURL value string POSTANON = "http://www.bungie.net/Default.aspx?wa=wsignin1.0"; //Get the ANON value string ANON = HTML.Remove(0, HTML.IndexOf("ANON")); ANON = ANON.Remove(0, ANON.IndexOf("value") + 7); ANON = ANON.Substring(0, ANON.IndexOf("\"")); ANON = HttpUtility.UrlEncode(ANON); //Get the ANONExp value string ANONExp = HTML.Remove(0, HTML.IndexOf("ANONExp")); ANONExp = ANONExp.Remove(0, ANONExp.IndexOf("value") + 7); ANONExp = ANONExp.Substring(0, ANONExp.IndexOf("\"")); ANONExp = HttpUtility.UrlEncode(ANONExp); //Get the t value string t = HTML.Remove(0, HTML.IndexOf("id=\"t\"")); t = t.Remove(0, t.IndexOf("value") + 7); t = t.Substring(0, t.IndexOf("\"")); t = HttpUtility.UrlEncode(t); //POST the Info and Accept the Bungie Cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTANON); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Encoding", "gzip,deflate"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "115"); http.CookieContainer = new CookieContainer(); http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; http.Expect = null; ostream = http.GetRequestStream(); int test = ANON.Length; int test1 = ANONExp.Length; int test2 = t.Length; buffer = encoding.GetBytes("ANON=" + ANON +"&ANONExp=" + ANONExp + "&t=" + t); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); //Here lies the problem, I am not returned the correct cookies. HttpWebResponse response3 = (HttpWebResponse)http.GetResponse(); GZipStream gzip = new GZipStream(response3.GetResponseStream(), CompressionMode.Decompress); readStream = new StreamReader(gzip); HTML = readStream.ReadToEnd(); //gets both cookies string[] strCookies2 = response3.Headers.GetValues(11); response3.Close(); } } } This has given me problems and I've put many hours into learning about HTTP protocols so any help would be appreciated. If there is an article detailing a similar log in to live.com feel free to point the way. I've been looking far and wide for any articles with working solutions. If I could be clearer, feel free to ask as this is my first time using Stack Overflow.

    Read the article

  • Monotouch - ICSharpCode.SharpZipLib giving an error

    - by Claudio
    Hy guys, I'm trying to generate a Zip File with ICSharpCode.SharpZipLib library but it's throwing a really weird error. Code: public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password) { ArrayList ar = GenerateFileList(inputFolderPath); // generate file list int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length; TrimLength += 1; //remove '\' FileStream ostream; byte[] obuffer; ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outputPathAndFile)); // create zip stream if (password != null && password != String.Empty) oZipStream.Password = password; oZipStream.SetLevel(9); // maximum compression ZipEntry oZipEntry; foreach (string Fil in ar) // for each file, generate a zipentry { oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); oZipStream.PutNextEntry(oZipEntry); if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { ostream = File.OpenRead(Fil); obuffer = new byte[ostream.Length]; ostream.Read(obuffer, 0, obuffer.Length); oZipStream.Write(obuffer, 0, obuffer.Length); } } oZipStream.Finish(); oZipStream.Close(); } private static ArrayList GenerateFileList(string Dir) { ArrayList fils = new ArrayList(); bool Empty = true; foreach (string file in Directory.GetFiles(Dir,"*.xml")) // add each file in directory { fils.Add(file); Empty = false; } if (Empty) { if (Directory.GetDirectories(Dir).Length == 0) // if directory is completely empty, add it { fils.Add(Dir + @"/"); } } foreach (string dirs in Directory.GetDirectories(Dir)) // recursive { foreach (object obj in GenerateFileList(dirs)) { fils.Add(obj); } } return fils; // return file list } Error: Unhandled Exception: System.NotSupportedException: CodePage 437 not supported at System.Text.Encoding.GetEncoding (Int32 codepage) [0x00000] in <filename unknown>:0 at ICSharpCode.SharpZipLib.Zip.ZipConstants.ConvertToArray (System.String str) [0x00000] in <filename unknown>:0 at ICSharpCode.SharpZipLib.Zip.ZipConstants.ConvertToArray (Int32 flags, System.String str) [0x00000] in <filename unknown>:0 at ICSharpCode.SharpZipLib.Zip.ZipOutputStream.PutNextEntry (ICSharpCode.SharpZipLib.Zip.ZipEntry entry) [0x00000] in <filename unknown>:0 at WpfPrototype1.MainInvoicesView.ZipFiles (System.String inputFolderPath, System.String outputPathAndFile, System.String password) [0x00000] in <filename unknown>:0 at WpfPrototype1.MainInvoicesView.<ViewDidLoad>m__6 (System.Object , System.EventArgs ) [0x00000] in <filename unknown>:0 at MonoTouch.UIKit.UIControlEventProxy.Activated () [0x00000] in <filename unknown>:0 at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr) at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00000] in <filename unknown>:0 at MonoTouch.UIKit.UIApplication.Main (System.String[] args) [0x00000] in <filename unknown>:0 at WpfPrototype1.Application.Main (System.String[] args) [0x00000] in <filename unknown>:0 How can I make this code support CodePage 437? Regards, Claudio

    Read the article

  • Turning temporary stringstream to c_str() in single statement

    - by AshleysBrain
    Consider the following function: void f(const char* str); Suppose I want to generate a string using stringstream and pass it to this function. If I want to do it in one statement, I might try: f((std::ostringstream() << "Value: " << 5).str().c_str()); // error This gives an error: 'str()' is not a member of 'basic_ostream'. OK, so operator<< is returning ostream instead of ostringstream - how about casting it back to an ostringstream? 1) Is this cast safe? f(static_cast<std::ostringstream&>(std::ostringstream() << "Value: " << 5).str().c_str()); // incorrect output Now with this, it turns out for the operator<<("Value: ") call, it's actually calling ostream's operator<<(void*) and printing a hex address. This is wrong, I want the text. 2) Why does operator<< on the temporary std::ostringstream() call the ostream operator? Surely the temporary has a type of 'ostringstream' not 'ostream'? I can cast the temporary to force the correct operator call too! f(static_cast<std::ostringstream&>(static_cast<std::ostringstream&>(std::ostringstream()) << "Value: " << 5).str().c_str()); This appears to work and passes "Value: 5" to f(). 3) Am I relying on undefined behavior now? The casts look unusual. I'm aware the best alternative is something like this: std::ostringstream ss; ss << "Value: " << 5; f(ss.str().c_str()); ...but I'm interested in the behavior of doing it in one line. Suppose someone wanted to make a (dubious) macro: #define make_temporary_cstr(x) (static_cast<std::ostringstream&>(static_cast<std::ostringstream&>(std::ostringstream()) << x).str().c_str()) // ... f(make_temporary_cstr("Value: " << 5)); Would this function as expected?

    Read the article

  • Debug-only ostreams in C++?

    - by Emanuel
    I've implemented an ostream for debug output which sends ends up sending the debug info to OutputDebugString. A typical use of it looks like this (where debug is an ostream object): debug << "some error\n"; For release builds, what's the least painful and most performant way to not output these debug statements?

    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

  • Implementing default constructors

    - by James
    Implement the default constructor, the constructors with one and two int parameters. The one-parameter constructor should initialize the first member of the pair, the second member of the pair is to be 0. Overload binary operator + to add the pairs as follows: (a, b) + (c, d) = (a + c, b + d); Overload the - analogously. Overload the * on pairs ant int as follows: (a, b) * c = (a * c, b * c). Write a program to test all the member functions and overloaded operators in your class definition. You will also need to write accessor (get) functions for each member. The definition of the class Pairs: class Pairs { public: Pairs(); Pairs(int first, int second); Pairs(int first); // other members and friends friend istream& operator>> (istream&, Pair&); friend ostream& operator<< (ostream&, const Pair&); private: int f; int s; }; Self-Test Exercise #17: istream& operator (istream& ins, Pair& second) { char ch; ins ch; // discard init '(' ins second.f; ins ch; // discard comma ',' ins second.s; ins ch; // discard final '(' return ins; } ostream& operator<< (ostream& outs, const Pair& second) { outs << '('; outs << second.f; outs << ", " ;// I followed the Author's suggestion here. outs << second.s; outs << ")"; return outs; }

    Read the article

  • C++ HW - defining classes - objects that have objects of other class problem in header file (out of

    - by kitfuntastik
    This is my first time with much of this code. With this instancepool.h file below I get errors saying I can't use vector (line 14) or have instance& as a return type (line 20). It seems it can't use the instance objects despite the fact that I have included them. #ifndef _INSTANCEPOOL_H #define _INSTANCEPOOL_H #include "instance.h" #include <iostream> #include <string> #include <vector> #include <stdlib.h> using namespace std; class InstancePool { private: unsigned instances;//total number of instance objects vector<instance> ipp;//the collection of instance objects, held in a vector public: InstancePool();//Default constructor. Creates an InstancePool object that contains no Instance objects InstancePool(const InstancePool& original);//Copy constructor. After copying, changes to original should not affect the copy that was created. ~InstancePool();//Destructor unsigned getNumberOfInstances() const;//Returns the number of Instance objects the the InstancePool contains. const instance& operator[](unsigned index) const; InstancePool& operator=(const InstancePool& right);//Overloading the assignment operator for InstancePool. friend istream& operator>>(istream& in, InstancePool& ip);//Overloading of the >> operator. friend ostream& operator<<(ostream& out, const InstancePool& ip);//Overloading of the << operator. }; #endif Here is the instance.h : #ifndef _INSTANCE_H #define _INSTANCE_H ///////////////////////////////#include "instancepool.h" #include <iostream> #include <string> #include <stdlib.h> using namespace std; class Instance { private: string filenamee; bool categoryy; unsigned featuress; unsigned* featureIDD; unsigned* frequencyy; string* featuree; public: Instance (unsigned features = 0);//default constructor unsigned getNumberOfFeatures() const; //Returns the number of the keywords that the calling Instance object can store. Instance(const Instance& original);//Copy constructor. After copying, changes to the original should not affect the copy that was created. ~Instance() { delete []featureIDD; delete []frequencyy; delete []featuree;}//Destructor. void setCategory(bool category){categoryy = category;}//Sets the category of the message. Spam messages are represented with true and and legit messages with false.//easy bool getCategory() const;//Returns the category of the message. void setFileName(const string& filename){filenamee = filename;}//Stores the name of the file (i.e. “spam/spamsga1.txt”, like in 1st assignment) in which the message was initially stored.//const string& trick? string getFileName() const;//Returns the name of the file in which the message was initially stored. void setFeature(unsigned i, const string& feature, unsigned featureID,unsigned frequency) {//i for array positions featuree[i] = feature; featureIDD[i] = featureID; frequencyy[i] = frequency; } string getFeature(unsigned i) const;//Returns the keyword which is located in the ith position.//const string unsigned getFeatureID(unsigned i) const;//Returns the code of the keyword which is located in the ith position. unsigned getFrequency(unsigned i) const;//Returns the frequency Instance& operator=(const Instance& right);//Overloading of the assignment operator for Instance. friend ostream& operator<<(ostream& out, const Instance& inst);//Overloading of the << operator for Instance. friend istream& operator>>(istream& in, Instance& inst);//Overloading of the >> operator for Instance. }; #endif Also, if it is helpful here is instance.cpp: // Here we implement the functions of the class apart from the inline ones #include "instance.h" #include <iostream> #include <string> #include <stdlib.h> using namespace std; Instance::Instance(unsigned features) { //Constructor that can be used as the default constructor. featuress = features; if (features == 0) return; featuree = new string[featuress]; // Dynamic memory allocation. featureIDD = new unsigned[featuress]; frequencyy = new unsigned[featuress]; return; } unsigned Instance::getNumberOfFeatures() const {//Returns the number of the keywords that the calling Instance object can store. return featuress;} Instance::Instance(const Instance& original) {//Copy constructor. filenamee = original.filenamee; categoryy = original.categoryy; featuress = original.featuress; featuree = new string[featuress]; for(unsigned i = 0; i < featuress; i++) { featuree[i] = original.featuree[i]; } featureIDD = new unsigned[featuress]; for(unsigned i = 0; i < featuress; i++) { featureIDD[i] = original.featureIDD[i]; } frequencyy = new unsigned[featuress]; for(unsigned i = 0; i < featuress; i++) { frequencyy[i] = original.frequencyy[i];} } bool Instance::getCategory() const { //Returns the category of the message. return categoryy;} string Instance::getFileName() const { //Returns the name of the file in which the message was initially stored. return filenamee;} string Instance::getFeature(unsigned i) const { //Returns the keyword which is located in the ith position.//const string return featuree[i];} unsigned Instance::getFeatureID(unsigned i) const { //Returns the code of the keyword which is located in the ith position. return featureIDD[i];} unsigned Instance::getFrequency(unsigned i) const { //Returns the frequency return frequencyy[i];} Instance& Instance::operator=(const Instance& right) { //Overloading of the assignment operator for Instance. if(this == &right) return *this; delete []featureIDD; delete []frequencyy; delete []featuree; filenamee = right.filenamee; categoryy = right.categoryy; featuress = right.featuress; featureIDD = new unsigned[featuress]; frequencyy = new unsigned[featuress]; featuree = new string[featuress]; for(unsigned i = 0; i < featuress; i++) { featureIDD[i] = right.featureIDD[i]; } for(unsigned i = 0; i < featuress; i++) { frequencyy[i] = right.frequencyy[i]; } for(unsigned i = 0; i < featuress; i++) { featuree[i] = right.featuree[i]; } return *this; } ostream& operator<<(ostream& out, const Instance& inst) {//Overloading of the << operator for Instance. out << endl << "<message file=" << '"' << inst.filenamee << '"' << " category="; if (inst.categoryy == 0) out << '"' << "legit" << '"'; else out << '"' << "spam" << '"'; out << " features=" << '"' << inst.featuress << '"' << ">" <<endl; for (int i = 0; i < inst.featuress; i++) { out << "<feature id=" << '"' << inst.featureIDD[i] << '"' << " freq=" << '"' << inst.frequencyy[i] << '"' << "> " << inst.featuree[i] << " </feature>"<< endl; } out << "</message>" << endl; return out; } istream& operator>>(istream& in, Instance& inst) { //Overloading of the >> operator for Instance. string word; string numbers = ""; string filenamee2 = ""; bool categoryy2 = 0; unsigned featuress2; string featuree2; unsigned featureIDD2; unsigned frequencyy2; unsigned i; unsigned y; while(in >> word) { if (word == "<message") {//if at beginning of message in >> word;//grab filename word for (y=6; word[y]!='"'; y++) {//pull out filename from between quotes filenamee2 += word[y];} in >> word;//grab category word if (word[10] == 's') categoryy2 = 1; in >> word;//grab features word for (y=10; word[y]!='"'; y++) { numbers += word[y];} featuress2 = atoi(numbers.c_str());//convert string of numbers to integer Instance tempp2(featuress2);//make a temporary Instance object to hold values read in tempp2.setFileName(filenamee2);//set temp object to filename read in tempp2.setCategory(categoryy2); for (i=0; i<featuress2; i++) {//loop reading in feature reports for message in >> word >> word >> word;//skip two words numbers = "";//reset numbers string for (int y=4; word[y]!='"'; y++) {//grab feature ID numbers += word[y];} featureIDD2 = atoi(numbers.c_str()); in >> word;// numbers = ""; for (int y=6; word[y]!='"'; y++) {//grab frequency numbers += word[y];} frequencyy2 = atoi(numbers.c_str()); in >> word;//grab actual feature string featuree2 = word; tempp2.setFeature(i, featuree2, featureIDD2, frequencyy2); }//all done reading in and setting features in >> word;//read in last part of message : </message> inst = tempp2;//set inst (reference) to tempp2 (tempp2 will be destroyed at end of function call) return in; } } } and instancepool.cpp: // Here we implement the functions of the class apart from the inline ones #include "instancepool.h" #include "instance.h" #include <iostream> #include <string> #include <vector> #include <stdlib.h> using namespace std; InstancePool::InstancePool()//Default constructor. Creates an InstancePool object that contains no Instance objects { instances = 0; ipp.clear(); } InstancePool::~InstancePool() { ipp.clear();} InstancePool::InstancePool(const InstancePool& original) {//Copy constructor. instances = original.instances; for (int i = 0; i<instances; i++) { ipp.push_back(original.ipp[i]); } } unsigned InstancePool::getNumberOfInstances() const {//Returns the number of Instance objects the the InstancePool contains. return instances;} const Instance& InstancePool::operator[](unsigned index) const {//Overloading of the [] operator for InstancePool. return ipp[index];} InstancePool& InstancePool::operator=(const InstancePool& right) {//Overloading the assignment operator for InstancePool. if(this == &right) return *this; ipp.clear(); instances = right.instances; for(unsigned i = 0; i < instances; i++) { ipp.push_back(right.ipp[i]); } return *this; } istream& operator>>(istream& in, InstancePool& ip) {//Overloading of the >> operator. ip.ipp.clear(); string word; string numbers; int total;//int to hold total number of messages in collection while(in >> word) { if (word == "<messagecollection"){ in >> word;//reads in total number of all messages for (int y=10; word[y]!='"'; y++){ numbers = ""; numbers += word[y]; } total = atoi(numbers.c_str()); for (int x = 0; x<total; x++) {//do loop for each message in collection in >> ip.ipp[x];//use instance friend function and [] operator to fill in values and create Instance objects and read them intot he vector } } } } ostream& operator<<(ostream& out, const InstancePool& ip) {//Overloading of the << operator. out << "<messagecollection messages=" << '"' << '>' << ip.instances << '"'<< endl << endl; for (int z=0; z<ip.instances; z++) { out << ip[z];} out << endl<<"</messagecollection>\n"; } This code is currently not writing to files correctly either at least, I'm sure it has many problems. I hope my posting of so much is not too much, and any help would be very much appreciated. Thanks!

    Read the article

  • friendship and operator overloading help

    - by sil3nt
    hello there, I have the following class #ifndef Container_H #define Container_H #include <iostream> using namespace std; class Container{ friend bool operator==(const Container &rhs,const Container &lhs); public: void display(ostream & out) const; private: int sizeC; // size of Container int capacityC; // capacity of dynamic array int * elements; // pntr to dynamic array }; ostream & operator<< (ostream & out, const Container & aCont); #endif and this source file #include "container.h" /*----------------------------********************************************* note: to test whether capacityC and sizeC are equal, must i add 1 to sizeC? seeing as sizeC starts off with 0?? */ Container::Container(int maxCapacity){ capacityC = maxCapacity; elements = new int [capacityC]; sizeC = 0; } Container::~Container(){ delete [] elements; } Container::Container(const Container & origCont){ //copy constructor? int i = 0; for (i = 0; i<capacityC; i++){ //capacity to be used here? (*this).elements[i] = origCont.elements[i]; } } bool Container::empty() const{ if (sizeC == 0){ return true; }else{ return false; } } void Container::insert(int item, int index){ if ( sizeC == capacityC ){ cout << "\n*** Next: Bye!\n"; return; // ? have return here? } if ( (index >= 0) && (index <= capacityC) ){ elements[index] = item; sizeC++; } if ( (index < 0) && (index > capacityC) ){ cout<<"*** Illegal location to insert--"<< index << ". Container unchanged. ***\n"; }//error here not valid? according to original a3? have i implemented wrong? } void Container::erase(int index){ if ( (index >= 0) && (index <= capacityC) ){ //correct here? legal location? int i = 0; while (i<capacityC){ //correct? elements[index] = elements[index+1]; //check if index increases here. i++; } sizeC=sizeC-1; //correct? updated sizeC? }else{ cout<<"*** Illegal location to be removed--"<< index << ". Container unchanged. ***\n"; } } int Container::size()const{ return sizeC; //correct? } /* bool Container::operator==(const Container &rhs,const Container &lhs){ int equal = 0, i = 0; for (i = 0; i < capacityC ; i++){ if ( rhs.elements[i] == lhs.elements[i] ){ equal++; } } if (equal == sizeC){ return true; }else{ return false; } } ostream & operator<< (ostream & out, const Container & aCont){ int i = 0; for (i = 0; i<sizeC; i++){ out<< aCont.elements[i] << " " << endl; } } */ I dont have the other functions in the header file (just a quikie). Anyways, the last two functions in "/* */" I cant get to work, what am I doing wrong here? the first function is to see whether the two arrays are equal to one another

    Read the article

  • templete class c++

    - by inna karpasas
    hi! i try to design a templete for my universty project. i wrote the follwing cod: #ifndef _LinkedList_H_ #define _LinkedList_H_ #include "Link.h" #include <ostream> template <class L>//error one class LinkedList { private: Link<L> *pm_head; Link<L> * pm_tail; int m_numOfElements; Link<L>* FindLink(L * dataToFind); public: LinkedList(); ~LinkedList(); int GetNumOfElements(){return m_numOfElements;} bool Add( L * data); L *FindData(L * data); template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two L* GetDataOnTop(); bool RemoveFromHead(); L* Remove(L * toRemove); this templete uses the link class templete #ifndef _Link_H_ #define _Link_H_ template <class T>//error 3 class Link { private: T* m_data; Link* m_next; Link* m_prev; public: Link(T* data); ~Link(void); bool Link::operator ==(const Link& other)const; /*getters*/ Link* GetNext()const {return m_next;} Link* GetPrev()const {return m_prev;} T* GetData()const {return m_data;} //setters void SetNext(Link* next) {m_next = next;} void SetPrev(Link* prev) {m_prev = prev;} void SetData(T* data) {m_data = data;} }; error one: shadows template parm class L' error two:declaration ofclass L' error three: shadows template parm `class T' i dont understand what is the problem. i can relly usr your help thank you :)

    Read the article

  • Why friend function is preferred to member function for operator<<

    - by skydoor
    When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ? class A { public: void operator<<(ostream& i) { i<<"Member function";} friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;} }; int main () { A a; A b; A c; cout<<a<<b<<c<<endl; a<<cout; return 0; } One point is that friend function enable us to use it like this cout<<a<<b<<c What other reasons?

    Read the article

  • Managing a log stream in C++ in a cout-like notation

    - by Andry
    Hello! I have a class in c++ in order to write log files for an application of mine. I have already built the class and it works, it is something like this: class Logger { std::string _filename; public: void print(std::string tobeprinted); } Well, it is intuitive that, in order to print a line in the log file, for an object of Logger, it is simply necessary to do the following: Logger mylogger("myfile.log"); mylogger.print(std::string("This is a log line")); Well. Using a method approach is not the same as using a much better pattern like << is. I would like to do the following: Logger mylogger("myfile.log"); mylogger << "This is a log line"; That's all. I suppose I must overload the << operator... But overloading using this signature (the classic one): ostream& operator<<(ostream& output, const MyObj& o); But I do not have a ostream... So, should I do as follows? Logger& operator<<(Logger& output, const std::string& o); Is this the right way? Thanks

    Read the article

  • Operator Overloading << in c++

    - by thlgood
    I'm a fresh man in C++. I write this simple program to practice Overlaoding. This is my code: #include <iostream> #include <string> using namespace std; class sex_t { private: char __sex__; public: sex_t(char sex_v = 'M'):__sex__(sex_v) { if (sex_v != 'M' && sex_v != 'F') { cerr << "Sex type error!" << sex_v << endl; __sex__ = 'M'; } } const ostream& operator << (const ostream& stream) { if (__sex__ == 'M') cout << "Male"; else cout << "Female"; return stream; } }; int main(int argc, char *argv[]) { sex_t me('M'); cout << me << endl; return 0; } When I compiler it, It print a lots of error message: The error message was in a mess. It's too hard for me to found useful message sex.cpp: ???‘int main(int, char**)’?: sex.cpp:32:10: ??: ‘operator<<’?‘std::cout << me’????? sex.cpp:32:10: ??: ???: /usr/include/c++/4.6/ostream:110:7: ??: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostre

    Read the article

  • Build problems when adding `__str__` method to Boost Python C++ class

    - by Rickard
    I have started to play around with boost python a bit and ran into a problem. I tried to expose a C++ class to python which posed no problems. But I can't seem to manage to implement the __str__ functionality for the class without getting build errors I don't understand. I'm using boost 1_42 prebuild by boostpro. I build the library using cmake and the vs2010 compiler. I have a very simple setup. The header-file (tutorial.h) looks like the following: #include <iostream> namespace TestBoostPython{ class TestClass { private: double m_x; public: TestClass(double x); double Get_x() const; void Set_x(double x); }; std::ostream &operator<<(std::ostream &ostr, const TestClass &ts); }; and the corresponding cpp-file looks like: #include <boost/python.hpp> #include "tutorial.h" using namespace TestBoostPython; TestClass::TestClass(double x) { m_x = x; } double TestClass::Get_x() const { return m_x; } void TestClass::Set_x(double x) { m_x = x; } std::ostream &operator<<(std::ostream &ostr, TestClass &ts) { ostr << ts.Get_x() << "\n"; return ostr; } BOOST_PYTHON_MODULE(testme) { using namespace boost::python; class_<TestClass>("TestClass", init<double>()) .add_property("x", &TestClass::Get_x, &TestClass::Set_x) .def(str(self)) ; } The CMakeLists.txt looks like the following: CMAKE_MINIMUM_REQUIRED(VERSION 2.8) project (testme) FIND_PACKAGE( Boost REQUIRED ) FIND_PACKAGE( Boost COMPONENTS python REQUIRED ) FIND_PACKAGE( PythonLibs REQUIRED ) set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREAD ON) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) INCLUDE_DIRECTORIES ( ${PYTHON_INCLUDE_PATH} ) add_library(testme SHARED tutorial.cpp) target_link_libraries(testme ${Boost_PYTHON_LIBRARY}) target_link_libraries(testme ${PYTHON_LIBRARY} The build error I get is the following: Compiling... tutorial.cpp C:\Program Files (x86)\boost\boost_1_42\boost/python/def_visitor.hpp(31) : error C2780: 'void boost::python::api::object_operators::visit(ClassT &,const char *,const boost::python::detail::def_helper &) const' : expects 3 arguments - 1 provided with [ U=boost::python::api::object ] C:\Program Files (x86)\boost\boost_1_42\boost/python/object_core.hpp(203) : see declaration of 'boost::python::api::object_operators::visit' with [ U=boost::python::api::object ] C:\Program Files (x86)\boost\boost_1_42\boost/python/def_visitor.hpp(67) : see reference to function template instantiation 'void boost::python::def_visitor_access::visit,classT>(const V &,classT &)' being compiled with [ DerivedVisitor=boost::python::api::object, classT=boost::python::class_, V=boost::python::def_visitor ] C:\Program Files (x86)\boost\boost_1_42\boost/python/class.hpp(225) : see reference to function template instantiation 'void boost::python::def_visitor::visit>(classT &) const' being compiled with [ DerivedVisitor=boost::python::api::object, W=TestBoostPython::TestClass, classT=boost::python::class_ ] .\tutorial.cpp(29) : see reference to function template instantiation 'boost::python::class_ &boost::python::class_::def(const boost::python::def_visitor &)' being compiled with [ W=TestBoostPython::TestClass, U=boost::python::api::object, DerivedVisitor=boost::python::api::object ] Does anyone have any idea on what went wrrong? If I remove the .def(str(self)) part from the wrapper code, everything compiles fine and the class is usable from python. I'd be very greatful for assistance. Thank you, Rickard

    Read the article

  • Exporting to XML, including embedded classes

    - by Andy
    I have an object config which has some properties. I can export this ok, however, it also has an ArrayList which relates to embedded classes which I can't get to appear when I export to XML. Any pointers would be helpful. Export Method public String exportXML(config conf, String path) { String success = ""; try { FileOutputStream fstream = new FileOutputStream(path); try { XMLEncoder ostream = new XMLEncoder(fstream); try { ostream.writeObject(conf); ostream.flush(); } finally { ostream.close(); } } finally { fstream.close(); } } catch (Exception ex) { success = ex.getLocalizedMessage(); } return success; } Config Class (some detail stripped to keep size down) public class config { protected String author = ""; protected String website = ""; private ArrayList questions = new ArrayList(); public config(){ } public void addQuestion(String name) { questions.add(new question(questions.size(), name)); } public void removeQuestion(int id) { questions.remove(id); for (int c = 0; c <= questions.size(); c++) { question q = (question) (questions.get(id)); q.setId(c); } questions.trimToSize(); } public config.question getQuestion(int id){ return (question)questions.get(id); } /** * There can be multiple questions per config. * Questions store all the information regarding what questions are * asked of the user, including images, descriptions, and answers. */ public class question { protected int id; protected String title; protected ArrayList answers; public question(int id, String title) { this.id = id; this.title = title; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void addAnswer(String name) { answers.add(new answer(answers.size(), name)); } public void removeAnswer(int id) { answers.remove(id); for (int c = 0; c <= answers.size(); c++) { answer a = (answer) (answers.get(id)); a.setId(c); } answers.trimToSize(); } public config.question.answer getAnswer(int id){ return (answer)answers.get(id); } public class answer { protected int id; protected String title; public answer(int id, String title) { this.id = id; this.title = title; } public int getId() { return id; } public void setId(int id) { this.id = id; } } } } Resultant XML File <?xml version="1.0" encoding="UTF-8"?> <java version="1.6.0_18" class="java.beans.XMLDecoder"> <object class="libConfig.config"> <void property="appName"> <string>xxx</string> </void> <void property="author"> <string>Andy</string> </void> <void property="website"> <string>www.example.com/dsx.xml</string> </void> </object> </java>

    Read the article

  • operator overloading of stream extraction operator in C++ help

    - by Crystal
    I'm having some trouble overloading my stream extraction operator in C++ for a hw assignment. I'm not really sure why I am getting these compile errors since I thought I was doing it right... Here is my code: Complex.h #ifndef COMPLEX_H #define COMPLEX_H class Complex { //friend ostream &operator<<(ostream &output, const Complex &complexObj) const; public: Complex(double = 0.0, double = 0.0); // constructor Complex operator+(const Complex &) const; // addition Complex operator-(const Complex &) const; // subtraction void print() const; // output private: double real; // real part double imaginary; // imaginary part }; #endif Complex.cpp #include <iostream> #include "Complex.h" using namespace std; // Constructor Complex::Complex(double realPart, double imaginaryPart) : real(realPart), imaginary(imaginaryPart) { } // addition operator Complex Complex::operator+(const Complex &operand2) const { return Complex(real + operand2.real, imaginary + operand2.imaginary); } // subtraction operator Complex Complex::operator-(const Complex &operand2) const { return Complex(real - operand2.real, imaginary - operand2.imaginary); } // Overload << operator ostream &Complex::operator<<(ostream &output, const Complex &complexObj) const { cout << '(' << complexObj.real << ", " << complexObj.imaginary << ')'; return output; // returning output allows chaining } // display a Complex object in the form: (a, b) void Complex::print() const { cout << '(' << real << ", " << imaginary << ')'; } main.cpp #include <iostream> #include "Complex.h" using namespace std; int main() { Complex x; Complex y(4.3, 8.2); Complex z(3.3, 1.1); cout << "x: "; x.print(); cout << "\ny: "; y.print(); cout << "\nz: "; z.print(); x = y + z; cout << "\n\nx = y + z: " << endl; x.print(); cout << " = "; y.print(); cout << " + "; z.print(); x = y - z; cout << "\n\nx = y - z: " << endl; x.print(); cout << " = "; y.print(); cout << " - "; z.print(); cout << endl; } Compile erros: complex.cpp(23) : error C2039: '<<' : is not a member of 'Complex' complex.h(5) : see declaration of 'Complex' complex.cpp(24) : error C2270: '<<' : modifiers not allowed on nonmember functions complex.cpp(25) : error C2248: 'Complex::real' : cannot access private member declared in class 'Complex' complex.h(13) : see declaration of 'Complex::real' complex.h(5) : see declaration of 'Complex' complex.cpp(25) : error C2248: 'Complex::imaginary' : cannot access private member declared in class 'Complex' complex.h(14) : see declaration of 'Complex::imaginary' complex.h(5) : see declaration of 'Complex' Thanks!

    Read the article

  • Overloading '-' for array subtraction

    - by Chris Wilson
    I am attempting to subtract two int arrays, stored as class members, using an overloaded - operator, but I'm getting some peculiar output when I run tests. The overload definition is Number& Number :: operator-(const Number& NumberObject) { for (int count = 0; count < NumberSize; count ++) { Value[count] -= NumberObject.Value[count]; } return *this; } Whenever I run tests on this, NumberObject.Value[count] always seems to be returning a zero value. Can anyone see where I'm going wrong with this? The line in main() where this subtraction is being carried out is cout << "The difference is: " << ArrayOfNumbers[0] - ArrayOfNumbers[1] << endl; ArrayOfNumbers contains two Number objects. The class declaration is #include <iostream> using namespace std; class Number { private: int Value[50]; int NumberSize; public: Number(); // Default constructor Number(const Number&); // Copy constructor Number(int, int); // Non-default constructor void SetMemberValues(int, int); // Manually set member values int GetNumberSize() const; // Return NumberSize member int GetValue() const; // Return Value[] member Number& operator-=(const Number&); }; inline Number operator-(Number Lhs, const Number& Rhs); ostream& operator<<(ostream&, const Number&); The full class definition is as follows: #include <iostream> #include "../headers/number.h" using namespace std; // Default constructor Number :: Number() {} // Copy constructor Number :: Number(const Number& NumberObject) { int Temp[NumberSize]; NumberSize = NumberObject.GetNumberSize(); for (int count = 0; count < NumberObject.GetNumberSize(); count ++) { Temp[count] = Value[count] - NumberObject.GetValue(); } } // Manually set member values void Number :: SetMemberValues(int NewNumberValue, int NewNumberSize) { NumberSize = NewNumberSize; for (int count = NewNumberSize - 1; count >= 0; count --) { Value[count] = NewNumberValue % 10; NewNumberValue = NewNumberValue / 10; } } // Non-default constructor Number :: Number(int NumberValue, int NewNumberSize) { NumberSize = NewNumberSize; for (int count = NewNumberSize - 1; count >= 0; count --) { Value[count] = NumberValue % 10; NumberValue = NumberValue / 10; } } // Return the NumberSize member int Number :: GetNumberSize() const { return NumberSize; } // Return the Value[] member int Number :: GetValue() const { int ResultSoFar; for (int count2 = 0; count2 < NumberSize; count2 ++) { ResultSoFar = ResultSoFar * 10 + Value[count2]; } return ResultSoFar; } Number& operator-=(const Number& Rhs) { for (int count = 0; count < NumberSize; count ++) { Value[count] -= Rhs.Value[count]; } return *this; } inline Number operator-(Number Lhs, const Number& Rhs) { Lhs -= Rhs; return Lhs; } // Overloaded output operator ostream& operator<<(ostream& OutputStream, const Number& NumberObject) { OutputStream << NumberObject.GetValue(); return OutputStream; }

    Read the article

  • Why can't I sort this container?

    - by Knowing me knowing you
    Please don't mind that there is no insert fnc and that data are hardcoded. The main purpouse of it is to correctly implement iterator for this container. //file Set.h #pragma once template<class T> class Set { template<class T> friend ostream& operator<<(ostream& out, const Set<T>& obj); private: T** myData_; std::size_t mySize_; std::size_t myIndex_; public: Set(); class iterator : public std::iterator<std::random_access_iterator_tag, T*> { private: T** itData_; public: iterator(T** obj) { itData_ = obj; } T operator*() const { return **itData_; } /*Comparing values of two iterators*/ bool operator<(const iterator& obj) { return **itData_ < **obj.itData_; } /*Substracting two iterators*/ difference_type operator-(const iterator& obj) { return itData_ - obj.itData_; } /*Moving iterator backward for value*/ iterator operator-(const int value) { return itData_ - value; } /*Adding two iterators*/ difference_type operator+(const iterator& obj) { return itData_ + obj.itData_; } /*Moving iterator forward for value*/ iterator operator+(const int value) { return itData_ + value; } bool operator!=(const iterator& obj) { return (itData_ != obj.itData_); } bool operator==(const iterator& obj) { return (itData_ == obj.itData_); } T** operator++() { return ++itData_; } T** operator--() { return --itData_; } }; iterator begin() const { return myData_; } iterator end() const { return myData_ + myIndex_; } }; template<class T> ostream& operator<<(ostream& out, const Set<T>& obj) { for (int i = 0;i < 3; ++i) { out << *obj.myData_[i] << "\n"; } return out; } //file Set_impl.h #pragma once #include "stdafx.h" #include "Set.h" template<class T> Set<T>::Set() { mySize_ = 3; myIndex_ = 3; myData_ = new T*[mySize_]; myData_[0] = new T(3); myData_[1] = new T(1); myData_[2] = new T(2); } //main include "stdafx.h" #include "Set_impl.h" int _tmain(int argc, _TCHAR* argv[]) { Set<int> a; Set<int>::iterator beg_ = a.begin(); Set<int>::iterator end_ = a.end(); std::sort(beg_,end_);//WONT SORT THIS RANGE cin.get(); return 0; } Why sort can't accept this iterators even though I've provided all operators needed for sort to work? I think the best way to check what's going on is to paste this code and run it first. Thanks

    Read the article

  • Sharing output streams through a JNI interface

    - by Chris Conway
    I am writing a Java application that uses a C++ library through a JNI interface. The C++ library creates objects of type Foo, which are duly passed up through JNI to Java. Suppose the library has an output function void Foo::print(std::ostream &os) and I have a Java OutputStream out. How can I invoke Foo::print from Java so that the output appears on out? Is there any way to coerce the OutputStream to a std::ostream in the JNI layer? Can I capture the output in a buffer the JNI layer and then copy it into out?

    Read the article

  • Looking for a better way to integrate a static list into a set of classes

    - by EvilTeach
    I'm trying to expand my sons interest from Warcraft 3 programming into C++ to broaden his horizons to a degree. We are planning on porting a little game that he wrote. The context goes something like this. There are Ships and Missiles, for which Ships will use Missiles and interact with them A Container exists which will hold 'a list' of ships. A Container exists which will hold 'a list' of planets. One can apply a function over all elements in the Container (for_each) Ships and Missles can be created/destroyed at any time New objects automatically insert themselves into the proper container. I cobbled a small example together to do that job, so we can talk about topics (list, templates etc) but I am not pleased with the results. #include <iostream> #include <list> using namespace std; /* Base class to hold static list in common with various object groups */ template<class T> class ObjectManager { public : ObjectManager ( void ) { cout << "Construct ObjectManager at " << this << endl; objectList.push_back(this); } virtual ~ObjectManager ( void ) { cout << "Destroy ObjectManager at " << this << endl; } void for_each ( void (*function)(T *) ) { for (objectListIter = objectList.begin(); objectListIter != objectList.end(); ++objectListIter) { (*function)((T *) *objectListIter); } } list<ObjectManager<T> *>::iterator objectListIter; static list<ObjectManager<T> *> objectList; }; /* initializer for static list */ template<class T> list<ObjectManager<T> *> ObjectManager<T>::objectList; /* A simple ship for testing */ class Ship : public ObjectManager<Ship> { public : Ship ( void ) : ObjectManager<Ship>() { cout << "Construct Ship at " << this << endl; } ~Ship ( void ) { cout << "Destroy Ship at " << this << endl; } friend ostream &operator<< ( ostream &out, const Ship &that ) { out << "I am a ship"; return out; } }; /* A simple missile for testing */ class Missile : public ObjectManager<Missile> { public : Missile ( void ) : ObjectManager<Missile>() { cout << "Construct Missile at " << this << endl; } ~Missile ( void ) { cout << "Destroy Missile at " << this << endl; } friend ostream &operator<< ( ostream &out, const Missile &that ) { out << "I am a missile"; return out; } }; /* A function suitable for the for_each function */ template <class T> void show ( T *it ) { cout << "Show: " << *it << " at " << it << endl; } int main ( void ) { /* Create dummy planets for testing */ Missile p1; Missile p2; /* Demonstrate Iterator */ p1.for_each(show); /* Create dummy ships for testing */ Ship s1; Ship s2; Ship s3; /* Demonstrate Iterator */ s1.for_each(show); return 0; } Specifically, The list is effectively embedded in each ship though the inheritance mechanism. One must have a ship, in order to access the list of ships. One must have a missile in order to be able to access the list of missiles. That feels awkward. My question boils down to "Is there a better way to do this?" Automatic object container creation Automatic object insertion Container access without requiring an object in the list to access it. I am looking for better ideas. All helpful entries get an upvote. Thanks Evil.

    Read the article

  • IF Statement has strange behavior

    - by BSchlinker
    I've developed a 'custom' cout, so that I can display text to console and also print it to a log file. This cout class is passed a different integer on initialization, with the integer representing the verbosity level of the message. If the current verbosity level is greater then or equal to the verbosity level of the message, the message should print. The problem is, I have messages printing even when the current verbosity level is too low. I went ahead and debugged it, expecting to find the problem. Instead, I found multiple scenarios where my if statements are not working as expected. The statement if(ilralevel_passed <= ilralevel_set) will sometimes proceed even if ilralevel_set is LESS then ilralevel_passed. You can see this behavior in the following picture (my apologizes for using Twitpic) http://twitpic.com/1xtx4g/full. Notice how ilralevel_set is equal to zero, and ilralevel_passed is equal to one. Yet, the if statement has returned true and is now moving forward to pass the line to cout. I've never seen this type of behavior before and I'm not exactly sure how to proceed debugging it. I'm not able to isolate the behavior either -- it only occurs in certain parts of my program. Any suggestions are appreciated as always. // Here is an example use of the function: // ilra_status << setfill('0') << setw(2) << dispatchtime.tm_sec << endl; // ilra_warning << "Dispatch time (seconds): " << mktime(&dispatchtime) << endl; // Here is the 'custom' cout function: #ifndef ILRA_H_ #define ILRA_H_ // System libraries #include <iostream> #include <ostream> #include <sstream> #include <iomanip> // Definitions #define ilra_talk ilra(__FUNCTION__,0) #define ilra_update ilra(__FUNCTION__,0) #define ilra_error ilra(__FUNCTION__,1) #define ilra_warning ilra(__FUNCTION__,2) #define ilra_status ilra(__FUNCTION__,3) // Statics static int ilralevel_set = 0; static int ilralevel_passed; // Classes class ilra { public: // constructor / destructor ilra(const std::string &funcName, int toset) { ilralevel_passed = toset; } ~ilra(){}; // enable / disable irla functions static void ilra_verbose_level(int toset){ ilralevel_set = toset; } // output template <class T> ilra &operator<<(const T &v) { if(ilralevel_passed <= ilralevel_set) std::cout << v; return *this; } ilra &operator<<(std::ostream&(*f)(std::ostream&)) { if(ilralevel_passed <= ilralevel_set) std::cout << *f; return *this; } }; // end of the class #endif /* ILRA_H_ */

    Read the article

  • Track/Display Array Index As Part Of Cout (C++)

    - by John Smith
    Hi, I have a command line C++ program that lets you enter basic information about a person (ID number, name, age, etc.) and I want to output to a console in the following manner: ------------------------------------------------------------------- Index ID # First Name Last Name Age ------------------------------------------------------------------- 0 1234 John Smith 25 The person objects are stored in an array of Persons and I've overload the ostream (<<) operator to print out all of the fields like you see. The dashed lines and header come from a displayHdg() function. Anyhow, I have not been able to figure out how to get the proper index value for the array. Ideally, I'd like to generate the indices for each line, but all my attempts have failed. The array is looped through and each object printed in the main() function, and the ostream is overloaded in a person class, so I tried to use global variables as well as static variables, and all of those produce incorrect numbering (i.e. show 0, 1 the first time (for 2 objects), then change to 1, 2 on the next display). Any ideas?

    Read the article

  • C++ Operator overloading - 'recreating the Vector'

    - by Wallter
    I am currently in a collage second level programing course... We are working on operator overloading... to do this we are to rebuild the vector class... I was building the class and found that most of it is based on the [] operator. When I was trying to implement the + operator I run into a weird error that my professor has not seen before (apparently since the class switched IDE's from MinGW to VS express...) (I am using Visual Studio Express 2008 C++ edition...) Vector.h #include <string> #include <iostream> using namespace std; #ifndef _VECTOR_H #define _VECTOR_H const int DEFAULT_VECTOR_SIZE = 5; class Vector { private: int * data; int size; int comp; public: inline Vector (int Comp = 5,int Size = 0) : comp(Comp), size(Size) { if (comp > 0) { data = new int [comp]; } else { data = new int [DEFAULT_VECTOR_SIZE]; comp = DEFAULT_VECTOR_SIZE; } } int size_ () const { return size; } int comp_ () const { return comp; } bool push_back (int); bool push_front (int); void expand (); void expand (int); void clear (); const string at (int); int operator[ ](int); Vector& operator+ (Vector&); Vector& operator- (const Vector&); bool operator== (const Vector&); bool operator!= (const Vector&); ~Vector() { delete [] data; } }; ostream& operator<< (ostream&, const Vector&); #endif Vector.cpp #include <iostream> #include <string> #include "Vector.h" using namespace std; const string Vector::at(int i) { this[i]; } void Vector::expand() { expand(size); } void Vector::expand(int n ) { int * newdata = new int [comp * 2]; if (*data != NULL) { for (int i = 0; i <= (comp); i++) { newdata[i] = data[i]; } newdata -= comp; comp += n; delete [] data; *data = *newdata; } else if ( *data == NULL || comp == 0) { data = new int [DEFAULT_VECTOR_SIZE]; comp = DEFAULT_VECTOR_SIZE; size = 0; } } bool Vector::push_back(int n) { if (comp = 0) { expand(); } for (int k = 0; k != 2; k++) { if ( size != comp ){ data[size] = n; size++; return true; } else { expand(); } } return false; } void Vector::clear() { delete [] data; comp = 0; size = 0; } int Vector::operator[] (int place) { return (data[place]); } Vector& Vector::operator+ (Vector& n) { int temp_int = 0; if (size > n.size_() || size == n.size_()) { temp_int = size; } else if (size < n.size_()) { temp_int = n.size_(); } Vector newone(temp_int); int temp_2_int = 0; for ( int j = 0; j <= temp_int && j <= n.size_() && j <= size; j++) { temp_2_int = n[j] + data[j]; newone[j] = temp_2_int; } //////////////////////////////////////////////////////////// return newone; //////////////////////////////////////////////////////////// } ostream& operator<< (ostream& out, const Vector& n) { for (int i = 0; i <= n.size_(); i++) { //////////////////////////////////////////////////////////// out << n[i] << " "; //////////////////////////////////////////////////////////// } return out; } Errors: out << n[i] << " "; error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const Vector' (or there is no acceptable conversion) return newone; error C2106: '=' : left operand must be l-value As stated above, I am a student going into Computer Science as my selected major I would appreciate tips, pointers, and better ways to do stuff :D

    Read the article

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