Search Results

Search found 84 results on 4 pages for 'stringstream'.

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

  • convert int to string for use in allegro function

    - by ace
    I am trying to run the following code using allegro. textout_ex(screen, font, numbComments , 100, 100, GREEN, BLACK); numbComments is an integer, the function prototype of this function is void textout_ex(BITMAP *bmp, const FONT *f, const char *s, int x, int y, int color, int bg); and i cannot, according to my understanding pass this integer in the third position. I therefore need to convert the integer into a string. I did it like this, but it didnt work. Help please? int score = numbComments; string Str; stringstream out; // YOU MUST INCLUDE <sstream> FOR THIS. out << score; Str = out.str(); and then tried to use the string Str, which didnt work

    Read the article

  • Compile error with initializer_list when trying to use it to initialize member value of class

    - by ilektron
    I am trying to make a class initializable from an initialization_list in a class constructor's constructor's initialization list. It works for a std::map, but not for my custom class. I don't see any difference other than templates are used in std::map. #include <iostream> #include <initializer_list> #include <string> #include <sstream> #include <map> using std::string; class text_thing { private: string m_text; public: text_thing() { } text_thing(text_thing& other); text_thing(std::initializer_list< std::pair<const string, const string> >& il); text_thing& operator=(std::initializer_list< std::pair<const string, const string> >& il); operator string() { return m_text; } }; class static_base { private: std::map<string, string> m_test_map; text_thing m_thing; static_base(); public: static static_base& getInstance() { static static_base instance; return instance; } string getText() { return (string)m_thing; } }; typedef std::pair<const string, const string> spair; text_thing::text_thing(text_thing& other) { m_text = other.m_text; } text_thing::text_thing(std::initializer_list< std::pair<const string, const string> >& il) { std::stringstream text_gen; for (auto& apair : il) { text_gen << "{" << apair.first << ", " << apair.second << "}" << std::endl; } } text_thing& text_thing::operator=(std::initializer_list< std::pair<const string, const string> >& il) { std::stringstream text_gen; for (auto& apair : il) { text_gen << "{" << apair.first << ", " << apair.second << "}" << std::endl; } return *this; } static_base::static_base() : m_test_map{{"test", "1"}, {"test2", "2"}}, // Compiler fine with this m_thing{{"test", "1"}, {"test2", "2"}} // Compiler doesn't like this { } int main() { std::cout << "Starting the program" << std::endl; std::cout << "The text thing: " << std::endl << static_base::getInstance().getText(); } I get this compiler output g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"static_base.d" -MT"static_base.d" -o "static_base.o" "../static_base.cpp" Finished building: ../static_base.cpp Building file: ../test.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"test.d" -MT"test.d" -o "test.o" "../test.cpp" ../test.cpp: In constructor ‘static_base::static_base()’: ../test.cpp:94:40: error: no matching function for call to ‘text_thing::text_thing(<brace-enclosed initializer list>)’ m_thing{{"test", "1"}, {"test2", "2"}} ^ ../test.cpp:94:40: note: candidates are: ../test.cpp:72:1: note: text_thing::text_thing(std::initializer_list<std::pair<const std::basic_string<char>, const std::basic_string<char> > >&) text_thing::text_thing(std::initializer_list< std::pair<const string, const string> >& il) ^ ../test.cpp:72:1: note: candidate expects 1 argument, 2 provided ../test.cpp:67:1: note: text_thing::text_thing(text_thing&) text_thing::text_thing(text_thing& other) ^ ../test.cpp:67:1: note: candidate expects 1 argument, 2 provided ../test.cpp:23:2: note: text_thing::text_thing() text_thing() ^ ../test.cpp:23:2: note: candidate expects 0 arguments, 2 provided make: *** [test.o] Error 1 Output of gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.8/lto-wrapper Target: x86_64-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.8.1-2ubuntu1~13.04' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu Thread model: posix gcc version 4.8.1 (Ubuntu 4.8.1-2ubuntu1~13.04) It compiles fine with the std::map constructed this way, and if I modify the static_base to return the strings from the maps, all is fine and dandy. Please help me understand what is going on here.

    Read the article

  • Is there such a thing as a C# style extension method in C++ ?

    - by Gary Willoughby
    I'm currently learning C++ and i run into the simple problem of converting an int to a string. I've worked around it using: string IntToString(int Number) { stringstream Stream; Stream << Number; return Stream.str(); } but though it would be more elegant to use something like: int x = 5; string y = x.toString(); but how do i add the toString() method to a built in type? or am i missing something totally fundamental?

    Read the article

  • How to raise an error, if the parsed number of a C++ stdlib stream is immediatly followed by a non whitespace character?

    - by Micha Wiedenmann
    In the following example, I didn't expect, that 1.2345foo would be parsed. Since I am reading data files, it is probably better to raise an error and notify the user. Is peek() the correct thing to do here? #include <iostream> #include <sstream> int main() { std::stringstream in("1.2345foo"); double x; in >> x; if (in) { std::cout << "good\n"; } else { std::cout << "bad\n"; } } Output good

    Read the article

  • C++ split string

    - by Mike
    I am trying to split a string using spaces as a delimiter. I would like to store each token in an array or vector. I have tried. string tempInput; cin >> tempInput; string input[5]; stringstream ss(tempInput); // Insert the string into a stream int i=0; while (ss >> tempInput){ input[i] = tempInput; i++; } The problem is that if i input "this is a test", the array only seems to store input[0] = "this". It does not contain values for input[2] through input[4]. I have also tried using a vector but with the same result.

    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

  • How can I have multiple layers in my map array?

    - by Manl400
    How do I load Levels in my game, as in Layer 1 would be Objects, Layer 2 would be Characters and so on. I only need 3 layers, and they will all be put on top of each other. i.e having a flower with a transparent background to be put on grass or dirt on the layer below.I would like to Read From the same file too. How would i go about doing this? Any help would be appreciated. I load the map from a level file which are just numbers corresponding to a tile in the tilesheet. Here is the level file [Layer1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [Layer2] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [Layer3] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 And here is the code that interprets it void LoadMap(const char *filename, std::vector< std::vector <int> > &map) { std::ifstream openfile(filename); if(openfile.is_open()) { std::string line, value; int space; while(!openfile.eof()) { std::getline(openfile, line); if(line.find("[TileSet]") != std::string::npos) { state = TileSet; continue; } else if (line.find("[Layer1]") != std::string::npos) { state = Map; continue; } switch(state) { case TileSet: if(line.length() > 0) tileSet = al_load_bitmap(line.c_str()); break; case Map: std::stringstream str(line); std::vector<int> tempVector; while(!str.eof()) { std::getline(str, value, ' '); if(value.length() > 0) tempVector.push_back(atoi(value.c_str())); } map.push_back(tempVector); break; } } } else { } } and this is how it draws the map. Also the tile sheet is 1280 by 1280 and the tilesizeX and tilesizeY is 64 void DrawMap(std::vector <std::vector <int> > map) { int mapRowCount = map.size(); for(int i, j = 0; i < mapRowCount; i ++) { int mapColCount = map[i].size(); for (int j = 0; j < mapColCount; ++j) { int tilesetIndex = map[i][j]; int tilesetRow = floor(tilesetIndex / TILESET_COLCOUNT); int tilesetCol = tilesetIndex % TILESET_COLCOUNT; al_draw_bitmap_region(tileSet, tilesetCol * TileSizeX, tilesetRow * TileSizeY, TileSizeX, TileSizeY, j * TileSizeX, i * TileSizeX, NULL); } } } EDIT: http://i.imgur.com/Ygu0zRE.jpg

    Read the article

  • Why does OpenGL seem to ignore my glBindTexture call?

    - by Killrazor
    I'm having problems making a simple sprite rendering. I load 2 different textures. Then, I bind these textures and draw 2 squares, one with each texture. But only the texture of the first rendered object is drawn in both squares. Its like if I'd only use a texture or as if glBindTexture don't work properly. I know that GL is a state machine, but I think that you only need to change active texture with glBindTexture. I load texture with this method: bool CTexture::generate( utils::CImageBuff* img ) { assert(img); m_image = img; CHECKGL(glGenTextures(1,&m_textureID)); CHECKGL(glBindTexture(GL_TEXTURE_2D,m_textureID)); CHECKGL(glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR)); CHECKGL(glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR)); //CHECKGL(glTexImage2D(GL_TEXTURE_2D,0,img->getBpp(),img->getWitdh(),img->getHeight(),0,img->getFormat(),GL_UNSIGNED_BYTE,img->getImgData())); CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->getWitdh(), img->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img->getImgData())); return true; } And I bind textures with this function: void CTexture::bind() { CHECKGL(glBindTexture(GL_TEXTURE_2D,m_textureID)); } Also, I draw sprites with this method void CSprite2D::render() { CHECKGL(glLoadIdentity()); CHECKGL(glEnable(GL_TEXTURE_2D)); CHECKGL(glEnable(GL_BLEND)); CHECKGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); m_texture->bind(); CHECKGL(glPushMatrix()); CHECKGL(glBegin(GL_QUADS)); CHECKGL(glTexCoord2f(m_textureAreaStart.s,m_textureAreaStart.t)); // 0,0 by default CHECKGL(glVertex3i(m_position.x,m_position.y,0)); CHECKGL(glTexCoord2f(m_textureAreaEnd.s,m_textureAreaStart.t)); // 1,0 by default CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y, 0)); CHECKGL(glTexCoord2f(m_textureAreaEnd.s, m_textureAreaEnd.t)); // 1,1 by default CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y + m_dimensions.y, 0)); CHECKGL(glTexCoord2f(m_textureAreaStart.s, m_textureAreaEnd.t)); // 0,1 by default CHECKGL(glVertex3i( m_position.x, m_position.y + m_dimensions.y,0)); CHECKGL(glPopMatrix()); CHECKGL(glDisable(GL_BLEND)); } Edit: I bring also the check error code: int CheckGLError(const char *GLcall, const char *file, int line) { GLenum errCode; //avoids infinite loop int errorCount = 0; while ( (errCode=glGetError()) != GL_NO_ERROR && ++errorCount < 3000) { utils::globalLogPtr log = utils::CGLogFactory::getLogInstance(); const GLubyte *errString; errString = gluErrorString(errCode); std::stringstream ss; ss << "In "<< __FILE__<<"("<< __LINE__<<") "<<"GL error with code: " << errCode<<" at file " << file << ", line " << line << " with message: " << errString << "\n"; log->addMessage(ss.str(),ZEL_APPENDER_GL,utils::LOGLEVEL_ERROR); } return 0; }

    Read the article

  • RapidXML, reading and saving values

    - by Layne
    Hello, I've worked myself through the rapidXML sources and managed to read some values. Now I want to change them and save them to my XML file: Parsing file and set a pointer void SettingsHandler::getConfigFile() { pcSourceConfig = parsing->readFileInChar(CONF); cfg.parse<0>(pcSourceConfig); } Reading values from XML void SettingsHandler::getDefinitions() { SettingsHandler::getConfigFile(); stGeneral = cfg.first_node("settings")->value(); /* stGeneral = 60 */ } Changing values and saving to file void SettingsHandler::setDefinitions() { SettingsHandler::getConfigFile(); stGeneral = "10"; cfg.first_node("settings")->value(stGeneral.c_str()); std::stringstream sStream; sStream << *cfg.first_node(); std::ofstream ofFileToWrite; ofFileToWrite.open(CONF, std::ios::trunc); ofFileToWrite << "<?xml version=\"1.0\"?>\n" << sStream.str() << '\0'; ofFileToWrite.close(); } Reading file into buffer char* Parser::readFileInChar(const char* p_pccFile) { char* cpBuffer; size_t sSize; std::ifstream ifFileToRead; ifFileToRead.open(p_pccFile, std::ios::binary); sSize = Parser::getFileLength(&ifFileToRead); cpBuffer = new char[sSize]; ifFileToRead.read( cpBuffer, sSize); ifFileToRead.close(); return cpBuffer; } However, it's not possible to save the new value. My code is just saving the original file with a value of "60" where it should be "10". Rgds Layne

    Read the article

  • Why boost property tree write_json saves everything as string? Is it possible to change that?

    - by pprzemek
    I'm trying to serialize using boost property tree write_json, it saves everything as strings, it's not that data are wrong, but I need to cast them explicitly every time and I want to use them somewhere else. (like in python or other C++ json (non boost) library) here is some sample code and what I get depending on locale: boost::property_tree::ptree root, arr, elem1, elem2; elem1.put<int>("key0", 0); elem1.put<bool>("key1", true); elem2.put<float>("key2", 2.2f); elem2.put<double>("key3", 3.3); arr.push_back( std::make_pair("", elem1) ); arr.push_back( std::make_pair("", elem2) ); root.put_child("path1.path2", arr); std::stringstream ss; write_json(ss, root); std::string my_string_to_send_somewhare_else = ss.str(); and my_string_to_send_somewhere_else is sth. like this: { "path1" : { "path2" : [ { "key0" : "0", "key1" : "true" }, { "key2" : "2.2", "key3" : "3.3" } ] } } Is there anyway to save them as the values, like: "key1" : true or "key2" : 2.2 ?

    Read the article

  • getting boost::gregorian dates from a string

    - by Chris H
    I asked a related question yesterday http://stackoverflow.com/questions/2612343/basic-boost-date-time-input-format-question It worked great for posix_time ptime objects. I'm have trouble adapting it to get Gregorian date objects. try { stringstream ss; ss << dateNode->GetText(); using boost::local_time::local_time_input_facet; //using boost::gregorian; ss.imbue(locale(locale::classic(), new local_time_input_facet("%a, %d %b %Y "))); ss.exceptions(ios::failbit); ss>>dayTime; } catch (...) { cout<<"Failed to get a date..."<<endl; //cout<<e.what()<<endl; throw; } The dateNode-GetText() function returns a pointer to a string of the form Sat, 10 Apr 2010 19:30:00 The problem is I keep getting an exception. So concretely the question is, how do I go from const char * of the given format, to a boost::gregorian::date object? Thanks again.

    Read the article

  • std::list iterator: get next element

    - by sheepsimulator
    I'm trying to build a string using data elements stored in a std::list, where I want commas placed only between the elements (ie, if elements are {A,B,C,D} in list, result string should be "A,B,C,D". This code does not work: typedef std::list< shared_ptr<EventDataItem> > DataItemList; // ... std::string Compose(DataItemList& dilList) { std::stringstream ssDataSegment; for(iterItems = dilList.begin(); iterItems != dilList.end(); iterItems++) { // Lookahead in list to see if next element is end if((iterItems + 1) == dilList.end()) { ssDataSegment << (*iterItems)->ToString(); } else { ssDataSegment << (*iterItems)->ToString() << ","; } } return ssDataSegment.str(); } How do I get at "the-next-item" in a std::list using an iterator? I would expect that it's a linked-list, why can't I get at the next item?

    Read the article

  • std::list : get next element

    - by sheepsimulator
    I'm trying to build a string using data elements stored in a std::list, where I want commas placed only between the elements (ie, if elements are {A,B,C,D} in list, result string should be "A,B,C,D". This code does not work: typedef std::list< shared_ptr<EventDataItem> > DataItemList; // ... std::string Compose(DataItemList& dilList) { std::stringstream ssDataSegment; for(iterItems = dilList.begin(); iterItems = dilList.end(); iterItems++) { // Lookahead in list to see if next element is end if((iterItems + 1) == dilList.end()) { ssDataSegment << (*iterItems)->ToString(); } else { ssDataSegment << (*iterItems)->ToString() << ","; } } return ssDataSegment.str(); } How do I get at "the-next-item" in a std::list using an iterator? I would expect that it's a linked-list, why can't I get at the next item?

    Read the article

  • std::string.resize() and std::string.length()

    - by dreamlax
    I'm relatively new to C++ and I'm still getting to grips with the C++ Standard Library. To help transition from C, I want to format a std::string using printf-style formatters. I realise stringstream is a more type-safe approach, but I find myself finding printf-style much easier to read and deal with (at least, for the time being). This is my function: using namespace std; string formatStdString(const string &format, ...) { va_list va; string output; size_t needed; size_t used; va_start(va, format); needed = vsnprintf(&output[0], 0, format.c_str(), va); output.resize(needed + 1); // for null terminator?? used = vsnprintf(&output[0], output.capacity(), format.c_str(), va); // assert(used == needed); va_end(va); return output; } This works, kinda. A few things that I am not sure about are: Do I need to make room for a null terminator, or is this unnecessary? Is capacity() the right function to call here? I keep thinking length() would return 0 since the first character in the string is a '\0'. Occasionally while writing this string's contents to a socket (using its c_str() and length()), I have null bytes popping up on the receiving end, which is causing a bit of grief, but they seem to appear inconsistently. If I don't use this function at all, no null bytes appear.

    Read the article

  • Do I have to bind an UDP socket in my client program, to receive data? (I always get WASEINVAL)...

    - by Incubbus
    Hey There, I have the following problem: I am starting WSA, then I am creating a UDP socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP) and try to recvfrom on this socket, but it always returns -1 and I get WSAEINVAL (10022)... I don´t know why?... When I bind the port, that does not happen... But it is very lame to bind the clients socket... (As far as I remember, i never had this problem before:/ )... Anyone knows why this happens?... (I am sending data to my server, which anwsers[ or at least, tries to^^])... Inc::STATS CConnection::_RecvData(sockaddr* addr, std::string &strData) { int ret, len, fromlen; //return code / length of the data / sizeof(sockaddr) char *buffer; //will hold the data char c; //recv length of the message fromlen = sizeof(sockaddr); ret = recvfrom(m_InSock, &c, 1, 0, addr, &fromlen); if(ret != 1) { #ifdef __MYDEBUG__ std::stringstream ss; ss << WSAGetLastError(); MessageBox(NULL, ss.str().c_str(), "", MB_ICONERROR | MB_OK); #endif return Inc::ERECV; }...

    Read the article

  • What is the nicest way to parse this in C++ ?

    - by ereOn
    Hi, In my program, I have a list of "server address" in the following format: host[:port] The brackets here, indicate that the port is optional. host can be a hostname, an IPv4 or IPv6 address. port, if present can be a numeric port number or a service string (like: "http" or "ssh"). If port is present and host is an IPv6 address, host must be in "bracket-enclosed" notation (Example: [::1]) Here are some valid examples: localhost localhost:11211 127.0.0.1:http [::1]:11211 ::1 [::1] And an invalid example: ::1:80 // Invalid: Is this the IPv6 address ::1:80 and a default port, or the IPv6 address ::1 and the port 80 ? ::1:http // This is not ambigous, but for simplicity sake, let's consider this is forbidden as well. My goal is to separate such entries in two parts (obviously host and port). I don't care if either the host or port are invalid as long as they don't contain a : (290.234.34.34.5 is ok for host, it will be rejected in the next process); I just want to separate the two parts, or if there is no port part, to know it somehow. I tried to do something with std::stringstream but everything I come up to seems hacky and not really elegant. How would you do this in C++ ? I don't mind answers in C but C++ is prefered. Any boost solution is welcome as well. Thank you.

    Read the article

  • C++ compiler error on template specialization

    - by user231536
    I would like to specialize a template method for a class C that is itself templated by an int parameter. How do I do this? template <int D=1> class C { static std::string foo () { stringstream ss; ss << D << endl; return ss.str();} }; template <class X> void test() { cout << "This is a test" << endl;} template <> template <int D> void test<C<D> > () {cout << C<D>::foo() << endl;} The specialization for test() fails with "Too many template parameter lists in declaration of void test()".

    Read the article

  • complete nub.. iostream file not found

    - by user1742389
    folks I am almost completely new to programming so please bear with me. I am using the first example from lydia.com c++ videos and failing. I am using Xcode 4.5.1 with a c++ command line project instead of eclipse and I am getting an error on compile of iostream file not found. the code is simple and I will include exactly what I have at the end of this message. I thought that iostream was a standard header that came with all even remotely recent versions of c++ compilers and am shocked to get this error and I cannot find any way to fix this. please tell me whats going on. #include <iostream> #include <stdio.h> #include <sstream> #include <vector> int main(int argc, char ** argv) { stringstream version; version << "GCC Version"; _GNUC_<<"."<<_GNUC_MINOR_<<"."<<_GNUC_PATCHLEVEL_<<_"\nVersion String: " <<_VERSION_; cout <<version.string() endl; vector<string> v={"one","two","three"}; for ( s : v ) { cout << s <<endl; } // insert code here... printf("Hello, World!\n"); return 0; } Thanks.

    Read the article

  • Jumping onto next string when the condition is met

    - by user98235
    This was a problem related to one of the past topcoder exam problems called HowEasy. Let's assume that we're given a sentence, for instance, "We a1re really awe~~~some" I just wanted to take get rid of every word in the sentence that doesn't contain alphabet characters, so in the above sentence, the desired output would be "We really" The below is the code I wrote (incomplete), and I don't know how to move on to the next string when the condition (the string contains a character that's not alphabet) is met. Could you suggest some revisions or methods that would allow me to do that? vect would be the vector of strings containing the desired output string param; cin>>param; stringstream ss(param); vector<string> vect; string c; while(ss >> c){ for(int i=0; i < c.length(); i++){ if(!(97<=int(c[i])&&int(c[i])<=122) && !(65<=int(c[i])&&int(c[i])<=90)){ //I want to jump onto next string once the above condition is met //and ignore string c; } vect.push_back(c); if (ss.peek() == ' '){ ss.ignore(); } } }

    Read the article

  • CSV Parser works in windows, not linux.

    - by ladookie
    I'm parsing a CSV file that looks like this: E1,E2,E7,E8,,, E2,E1,E3,,,, E3,E2,E8,,, E4,E5,E8,E11,,, I store the first entry in each line in a string, and the rest go in a vector of strings: while (getline(file_input, line)) { stringstream tokenizer; tokenizer << line; getline(tokenizer, roomID, ','); vector<string> aVector; while (getline(tokenizer, adjRoomID, ',')) { if (!adjRoomID.empty()) { aVector.push_back(adjRoomID); } } Room aRoom(roomID, aVector); rooms.addToTail(aRoom); } In windows this works fine, however in Linux the first entry of each vector mysteriously loses the first character. For Example in the first iteration through the while loop: roomID would be E1 and aVector would be 2 E7 E8 then the second iteration: roomID would be E2 and aVector would be 1 E3 Notice the missing E's in the first entry of aVector. when I put in some debugging code it appears that it is initially being stored correctly in the vector, but then something overwrites it. Kudos to whoever figures this one out. Seems bizarre to me. rooms is declared as such: DLList<Room> rooms where DLList stands for Doubly-Linked list.

    Read the article

  • Trying to instantiate a class member in C++ with a variable name

    - by MarcZero
    Hello. I am writing a program for class that is asking us to create a class of "book". We are then supposed to create new instantiations of that class upon demand from the user. I am new to C++ so I am attempting to code this out but am running into a problem. The main problem is how do I instantiate a class with a variable if I don't know how many I will have to do ahead of time. The user could ask to add 1 book or 1000. I am looking at this basic code: This is the simple code I started with. I wanted to have an index int keep a number and have the book class I create be called by that int (0, 1, 2, etc...) So I attempted to convert the incoming index int into a string, but I'm kind of stuck from here. void addBook(int index){ string bookName; std::stringstream ss; ss << index; book bookName; cout << "Enter the Books Title: "; cin >> bookName.title; } But obviously this doesn't work as "bookName" is a string to the computer and not the class member I tried to create. All of the tutorials I have seen online and in my text show the classes being instantiated with names in the code, but I just don't know how to make it variable so I can create any amount of "books" that the user might want. Any insight on this would be appreciated. Thank you for your time.

    Read the article

  • Problem with combination boost::exception and boost::variant

    - by Rick
    Hello all, I have strange problem with two-level variant struct when boost::exception is included. I have following code snippet: #include <boost/variant.hpp> #include <boost/exception/all.hpp> typedef boost::variant< int > StoredValue; typedef boost::variant< StoredValue > ExpressionItem; inline std::ostream& operator << ( std::ostream & os, const StoredValue& stvalue ) { return os;} inline std::ostream& operator << ( std::ostream & os, const ExpressionItem& stvalue ) { return os; } When I try to compile it, I have following error: boost/exception/detail/is_output_streamable.hpp(45): error C2593: 'operator <<' is ambiguous test.cpp(11): could be 'std::ostream &operator <<(std::ostream &,const ExpressionItem &)' [found using argument-dependent lookup] test.cpp(8): or 'std::ostream &operator <<(std::ostream &,const StoredValue &)' [found using argument-dependent lookup] 1> while trying to match the argument list '(std::basic_ostream<_Elem,_Traits>, const boost::error_info<Tag,T>)' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> and 1> [ 1> Tag=boost::tag_original_exception_type, 1> T=const type_info * 1> ] Code snippet is simplified as much as possible, in the real code are structures much more complicated and each variant has five sub-types. When i remove #include and try following test snippet, program is compiled correctly: void TestVariant() { ExpressionItem test; std::stringstream str; str << test; } Could someone please advise me how to define operators << in order to function even when using boost::Exception ? Thanks and regards Rick

    Read the article

  • Initialize a Variable Again.

    - by SoulBeaver
    That may sound a little confusing. Basically, I have a function CCard newCard() { /* Used to store the string variables intermittantly */ std::stringstream ssPIN, ssBN; int picker1, picker2; int pin, bankNum; /* Choose 5 random variables, store them in stream */ for( int loop = 0; loop < 5; ++loop ) { picker1 = rand() % 8 + 1; picker2 = rand() % 8 + 1; ssPIN << picker1; ssBN << picker2; } /* Convert them */ ssPIN >> pin; ssBN >> bankNum; CCard card( pin, bankNum ); return card; } that creates a new CCard variable and returns it to the caller CCard card = newCard(); My teacher advised me that doing this is a violation of OOP principles and has to be put in the class. He told me to use this method as a constructor. Which I did: CCard::CCard() { m_Sperre = false; m_Guthaben = rand() % 1000; /* Work */ /* Convert them */ ssPIN >> m_Geheimzahl; ssBN >> m_Nummer; } All variables with m_ are member variables. However, the constructor works when I initialize the card normally CCard card(); at the start of the program. However, I also have a function, that is supposed to create a new card and return it to the user, this function is now broken. The original command: card = newCard(); isn't available anymore, and card = new CCard(); doesn't work. What other options do I have? I have a feeling using the constructor won't work, and that I probably should just create a class method newCard, but I want to see if it is somehow at all possible to do it the way the teacher wanted. This is creating a lot of headaches for me. I told the teacher that this is a stupid idea and not everything has to be classed in OOP. He has since told me that Java or C# don't allow code outside of classes, which sounds a little incredible. Not sure that you can do this in C++, especially when templated functions exist, or generic algorithms. Is it true that this would be bad code for OOP in C++ if I didn't force it into a class?

    Read the article

  • Convert string from getline into a number

    - by haskellguy
    I am trying to create a 2D array with vectors. I have a file that has for each line a set of numbers. So what I did I implemented a split function that every time I have a new number (separated by \t) it splits that and add it to the vector vector<double> &split(const string &s, char delim, vector<double> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { cout << item << endl; double number = atof(item.c_str()); cout << number; elems.push_back(number); } return elems; } vector<double> split(const string &s, char delim) { vector<double> elems; split(s, delim, elems); return elems; } After that I simply iterate through it. int main() { ifstream file("./data/file.txt"); string row; vector< vector<double> > matrix; int line_count = -1; while (getline(file, row)) { line_count++; if (line_count <= 4) continue; vector<double> cols = split(row, '\t'); matrix.push_back(cols); } ... } Now my issues is in this bit here: while (getline(ss, item, delim)) { cout << item << endl; double number = atof(item.c_str()); cout << number; Where item.c_str() is converted to a 0. Shouldn't that be still a string having the same value as item? It works on a separate example if I do straight from string to c_string, but when I use this getline I end up in this error situation, hints?

    Read the article

  • template; Point<2, double>; Point<3, double>

    - by Oops
    Hi, I want to create my own Point struct it is only for purposes of learning C++. I have the following code: template <int dims, typename T> struct Point { T X[dims]; Point(){} Point( T X0, T X1 ) { X[0] = X0; X[1] = X1; } Point( T X0, T X1, T X2 ) { X[0] = X0; X[1] = X1; X[2] = X2; } Point<dims, int> toint() { //how to distinguish between 2D and 3D ??? Point<dims, int> ret = Point<dims, int>( (int)X[0], (int)X[1]); return ret; } std::string str(){ //how to distinguish between 2D and 3D ??? std::stringstream s; s << "{ X0: " << X[0] << " | X1: " << X[1] << " }"; return s.str(); } }; int main(void) { Point<2, double> p2d = Point<2, double>( 12.3, 45.6 ); Point<3, double> p3d = Point<3, double>( 12.3, 45.6, 78.9 ); Point<2, int> p2i = p2d.toint(); //OK Point<3, int> p3i = p3d.toint(); //m??? std::cout << p2d.str() << std::endl; //OK std::cout << p3d.str() << std::endl; //m??? std::cout << p2i.str() << std::endl; //m??? std::cout << p3i.str() << std::endl; //m??? char c; std::cin >> c; return 0; } of couse until now the output is not what I want. my questions is: how to take care of the dimensions of the Point (2D or 3D) in member functions of the Point? many thanks in advance Oops

    Read the article

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