Search Results

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

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

  • stringstream problem - vector iterator not dereferencable

    - by andreas
    Hello I've got a problem with the following code snippet. It is related to the stringstream "stringstream css(cv.back())" bit. If it is commented out the program will run ok. It is really weird, as I keep getting it in some of my programs, but if I just create a console project the code will run fine. In some of my Win32 programs it will and in some it won't (then it will return "vector iterator not dereferencable" but it will compile just fine). Any ideas at all would be really appreciated. Thanks! vector<double> cRes(2); vector<double> pRes(2); int readTimeVects2(vector<double> &cRes, vector<double> &pRes){ string segments; vector<string> cv, pv, chv, phv; ifstream cin("cm.txt"); ifstream pin("pw.txt"); ifstream chin("hm.txt"); ifstream phin("hw.txt"); while (getline(cin,segments,'\t')) { cv.push_back(segments); } while (getline(pin,segments,'\t')) { pv.push_back(segments); } while (getline(chin,segments,'\t')) { chv.push_back(segments); } while (getline(phin,segments,'\t')) { phv.push_back(segments); } cin.close(); pin.close(); chin.close(); phin.close(); stringstream phss(phv.front()); phss >> pRes[0]; phss.clear(); stringstream chss(chv.front()); chss >> cRes[0]; chss.clear(); stringstream pss(pv.back()); pss >> pRes[1]; pss.clear(); stringstream css(cv.back()); css >> cRes[1]; css.clear(); return 0; }

    Read the article

  • C++ stringstream, string, and char* conversion confusion

    - by Graphics Noob
    My question can be boiled down to, where does the string returned from stringstream.str().c_str() live in memory, and why can't it be assigned to a const char*? This code example will explain it better than I can #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream ss("this is a string\n"); string str(ss.str()); const char* cstr1 = str.c_str(); const char* cstr2 = ss.str().c_str(); cout << cstr1 // Prints correctly << cstr2; // ERROR, prints out garbage system("PAUSE"); return 0; } The assumption that stringstream.str().c_str() could be assigned to a const char* led to a bug that took me a while to track down. For bonus points, can anyone explain why replacing the cout statement with cout << cstr // Prints correctly << ss.str().c_str() // Prints correctly << cstr2; // Prints correctly (???) prints the strings correctly? I'm compiling in Visual Studio 2008.

    Read the article

  • Ways std::stringstream can set fail/bad bit?

    - by Evan Teran
    A common piece of code I use for simple string splitting looks like this: inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } Someone mentioned that this will silently "swallow" errors occurring in std::getline. And of course I agree that's the case. But it occurred to me, what could possibly go wrong here in practice that I would need to worry about. basically it all boils down to this: inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } if(ss.fail()) { // *** How did we get here!? *** } return elems; } A stringstream is backed by a string, so we don't have to worry about any of the issues associated with reading from a file. There is no type conversion going on here since getline simply reads until it sees a newline or EOF. So we can't get any of the errors that something like boost::lexical_cast has to worry about. I simply can't think of something besides failing to allocate enough memory that could go wrong, but that'll just throw a std::bad_alloc well before the std::getline even takes place. What am I missing?

    Read the article

  • C++ std::stringstream seemingly causes thread to hang or die under SunOS

    - by stretch
    I have an application developed under Linux with GCC 4.2 which makes quite heacy use of stringstreams to wrap and unwrap data being sent over the wire. (Because the Grid API I'm using demands it). Under Linux everything is fine but when I deploy to SunOS (v5.10 running SPARC) and compile with GCC 3.4.6 the app hangs when it reaches the point at which stringstreams are used. In more detail: The main thread accepts requests from clients and starts a new pthread to handle each request. The child thread uses stringstreams to pack data. When the child thread gets to that point it seems to hang for a second and then die. The main thread is unaffected. Are there any known issues with stringstream and GCC 3.4.6 or SunOS or SPARCs? I didn't find anything yet... Can anyone suggest a better way to pack and unpack large amounts of data a strings or byte streams? Apologies for not posting code but this to me seems more involved than a simple syntax error. All the same, the thread crashes: std::stringstream mystringstream; //not here mystringstream << "some data: "; //but here That is, I can declare the stringstream but when I try to use it something goes wrong.

    Read the article

  • C++ Stringstream int to string but returns null

    - by jumm
    Hi below is my function: string Employee::get_print(void) { string out_string; stringstream ss; ss << e_id << " " << type << endl; out_string = ss.str(); return out_string; } e_id and type are int and they contain values from the class Employee. But when I pass them into the stringstream they just clear the string when I try to out put it. But if I don't have a int in the ss << "Some text" << endl; this output fine. What am I doing wrong =S

    Read the article

  • C++ stringstream reads all zero's

    - by user69514
    I have a file which contains three integers per line. When I read the line I use a stringstream to separate the values, but it only reads the first value as it is. The other two are read as zero's. ifstream inputstream(filename.c_str()); if( inputstream.is_open() ){ string line; stringstream ss; while( getline(inputstream, line) ){ //check line and extract elements int id; double income; int members; ss.clear(); ss.str(line); ss >> id >> income >> members; In the case above, id is extracted correctly, but income, and members get assigned zero instead of the actual value.

    Read the article

  • std::stringstream GCC Abnormal Behavior

    - by FlorianZ
    I have a very interesting problem with compiling a short little program on a Mac (GCC 4.2). The function below would only stream chars or strings into the stringstream, but not anything else (int, double, float, etc.) In fact, the fail flag is set if I attempt to convert for example an int into a string. However, removing the preprocessor flag: _GLIBCXX_DEBUG=1, which is set by default in XCode for the debug mode, will yield the desired results / correct behavior. Here is the simple function I am talking about. value is template variable of type T. Tested for int, double, float (not working), char and strings (working). template < typename T > const std::string Attribute<T>::getValueAsString() const { std::ostringstream stringValue; stringValue << value; return stringValue.str(); } Any ideas what I am doing wrong, why this doesn't work, or what the preprocessor flag does to make this not work anymore? Thanks!

    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

  • Is is possible to stringstream this way? to convert from string to int?

    - by John
    Is it possible to stringstream like this? I am trying to read with ifstream and convert it. string things = "10 11 12 -10"; int i1; int i2; int i3; int i4; stringstream into; into << things; into >> i1; into >> i2; into >> i3; into >> i4; I expect it to be : i1 = 10 i2 = 11 i3 = 12 i4 = -10 is that correct? Can the same stringstream variable be used multiple times? When I tried, the first time was ok but everything else later on is just 0.

    Read the article

  • Uncompressing zlib data using boost::iostreams::filtering_streambuf trouble

    - by GuitaringEgg
    I'm trying to write a small class that will load the chunk data from part of a minecraft world file. I'm to the point where I have stored some data in a char array which was compressed with zlib and need to decompress it. I'm trying to use the boost filtering_streambuf to do this. char * rawChunk = new char[length - 1]; // Load chunk data stringstream ssRawChunk(rawChunk); boost::iostreams::filtering_istream in; in.push(boost::iostreams::zlib_decompressor()); in.push(ssRawChunk); stringstream ssOut; boost::iostreams::copy(in, ssOut); My problem is that rawChunk contains null data, so when coping data from (char*) rawChunk to (stringstream) ssRawChunk, it terminates at ~257 instead of the expected length 2154. Is there any way to use filtering_streambuf without stringstream to allow for null data or is there a way to stop stringstream to not terminate on null data?

    Read the article

  • Equivalent of %02d with std::stringstream?

    - by Andreas Brinck
    I wan't to output an integer to a std::stringstream with the equivalent format of printf's %02d. Is there an easier way to achieve this than: std::stringstream stream; stream.setfill('0'); stream.setw(2); stream << value; Is it possible to stream some sort of format flags to the stringstream, something like (pseudocode): stream << flags("%02d") << value;

    Read the article

  • C++: concatenate ints in an array?

    - by Nate
    As part of a homework assignment I need to concatenate certain values in an array in C++. So, for example if I have: int v[] = {0,1,2,3,4} I may need at some point to concatenate v[1] - v[4] so that I get an int with the value 1234. I got it working using stringstream, by appending the values onto the stringstream and then converting back to an integer. However, throughout the program there will eventually be about 3 million different permutations of v[] passed to my toInt() function, and the stringstream seems rather expensive (at least when dealing with that many values). it's working, but very slow and I'm trying to do whatever I can to optimize it. Is there a more optimal way to concatenate ints in an array in C++? I've done some searching and nearly everywhere seems to just suggest using stringstream (which works, but seems to be slowing my program down a lot). EDIT: Just clarifying, I do need the result to be an int.

    Read the article

  • Parse int to string with stringstream

    - by SoulBeaver
    Well! I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution. I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999]. As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream. So my code looked like this: // tempTotal is my int value I want converted. void toString( int tempTotal, string &str ) { ostringstream ss; // C++ Standard compliant method. ss << tempTotal; str = ss.str(); // Overwrite referenced value of given string. } and the function calling it was: else { toString( tempTotal, store ); cout << loop1 << " x " << loop2 << "= " << store << endl; } So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there. Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal. All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know. So even though I feel this is a really, really lame question, I just have to ask: How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.

    Read the article

  • Using stringstream instead of `sscanf` to parse a fixed-format string

    - by John Dibling
    I would like to use the facilities provided by stringstream to extract values from a fixed-format string as a type-safe alternative to sscanf. How can I do this? Consider the following specific use case. I have a std::string in the following fixed format: YYYYMMDDHHMMSSmmm Where: YYYY = 4 digits representing the year MM = 2 digits representing the month ('0' padded to 2 characters) DD = 2 digits representing the day ('0' padded to 2 characters) HH = 2 digits representing the hour ('0' padded to 2 characters) MM = 2 digits representing the minute ('0' padded to 2 characters) SS = 2 digits representing the second ('0' padded to 2 characters) mmm = 3 digits representing the milliseconds ('0' padded to 3 characters) Previously I was doing something along these lines: string s = "20101220110651184"; unsigned year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0; sscanf(s.c_str(), "%4u%2u%2u%2u%2u%2u%3u", &year, &month, &day, &hour, &minute, &second, &milli ); The width values are magic numbers, and that's ok. I'd like to use streams to extract these values and convert them to unsigneds in the interest of type safety. But when I try this: stringstream ss; ss << "20101220110651184"; ss >> setw(4) >> year; year retains the value 0. It should be 2010. How do I do what I'm trying to do? I can't use Boost or any other 3rd party library, nor can I use C++0x.

    Read the article

  • how do I check if a c++ string is an int?

    - by user342231
    when I use getline, I would input a bunch of strings or numbers, but I only want the while loop to output the "word" if it is not a number. so is there any way to check if "word" is a number or not, I know I could use atoi() for c-strings but how about for strings of the string class int main () { stringstream ss (stringstream::in | stringstream::out); string word; string str; getline(cin,str); ss<<str; while(ss>>word) { //if( ) cout<<word<<endl; } }

    Read the article

  • Why was std::strstream deprecated?

    - by andand
    I recently discovered that std::strstream has been deprecated in favor of std::stringstream. It's been a while since I've needed it, but it was useful in its way for what I needed to do at the time. My question is why was this decision made, and what benefits does std::stringstream provide that are absent from std::strstream?

    Read the article

  • Can someone explain to me why my output is this? And how would I correct my output?

    - by user342231
    /* in this slice of code I get an output of bbb 55 66 77 88 aaa the output I expect and want is bbb 55 66 77 88 bbb because I reassign ss from log[0] to log[1] So my question is why is the output different from what I expect and how do I change it to what I want? */ int w,x,y,z; stringstream ss (stringstream::in | stringstream::out); string word; string log[2]; log[0]="aaa 11 22 33 44"; log[1]="bbb 55 66 77 88"; ss<<log[0]; ss>>word; int k=0; ss>>w>>x>>y>>z; k++; ss<<log[k]; cout<<log[k]<<endl; ss>>word; cout<<word<<endl; return 0;

    Read the article

  • Capture data read from file into string stream Java

    - by halluc1nati0n
    I'm coming from a C++ background, so be kind on my n00bish queries... I'd like to read data from an input file and store it in a stringstream. I can accomplish this in an easy way in C++ using stringstreams. I'm a bit lost trying to do the same in Java. Following is a crude code/way I've developed where I'm storing the data read line-by-line in a string array. I need to use a string stream to capture my data into (rather than use a string array).. Any help? char dataCharArray[] = new char[2]; int marker=0; String inputLine; String temp_to_write_data[] = new String[100]; // Now, read from output_x into stringstream FileInputStream fstream = new FileInputStream("output_" + dataCharArray[0]); // Convert our input stream to a BufferedReader BufferedReader in = new BufferedReader (new InputStreamReader(fstream)); // Continue to read lines while there are still some left to read while ((inputLine = in.readLine()) != null ) { // Print file line to screen // System.out.println (inputLine); temp_to_write_data[marker] = inputLine; marker++; }

    Read the article

  • Read multiple strings from a file C++

    - by user69514
    Hi I need to read different values stored in a file one by one. So I was thinking I can use ifstream to open the file, but since the file is set up in such a way that a line might contain three numbers, and the other line one number or two numbers I'm not sure how to read each number one by one. I was thinking of using stringstream but I'm not sure if that would work. The file is a format like this. 52500.00 64029.50 56000.00 65500.00 53780.00 77300.00 44000.50 80100.20 90000.00 41000.00 60500.50 72000.00 I need to read each number and store it in a vector. What is the best way to accomplish this? Reading one number at a time even though each line contains a different amount of numbers?

    Read the article

  • std::basic_stringstream<unsigned char> won't compile with MSVC 10

    - by Michael J
    I'm trying to get UTF-8 chars to co-exist with ANSI 8-bit chars. My strategy has been to represent utf-8 chars as unsigned char so that appropriate overloads of functions can be used for the two character types. e.g. namespace MyStuff { typedef uchar utf8_t; typedef std::basic_string<utf8_t> U8string; } void SomeFunc(std::string &s); void SomeFunc(std::wstring &s); void SomeFunc(MyStuff::U8string &s); This all works pretty well until I try to use a stringstream. std::basic_ostringstream<MyStuff::utf8_t> ostr; ostr << 1; MSVC Visual C++ Express V10 won't compile this: c:\program files\microsoft visual studio 10.0\vc\include\xlocmon(213): warning C4273: 'id' : inconsistent dll linkage c:\program files\microsoft visual studio 10.0\vc\include\xlocnum(65) : see previous definition of 'public: static std::locale::id std::numpunct<unsigned char>::id' c:\program files\microsoft visual studio 10.0\vc\include\xlocnum(65) : while compiling class template static data member 'std::locale::id std::numpunct<_Elem>::id' with [ _Elem=Tk::utf8_t ] c:\program files\microsoft visual studio 10.0\vc\include\xlocnum(1149) : see reference to function template instantiation 'const _Facet &std::use_facet<std::numpunct<_Elem>>(const std::locale &)' being compiled with [ _Facet=std::numpunct<Tk::utf8_t>, _Elem=Tk::utf8_t ] c:\program files\microsoft visual studio 10.0\vc\include\xlocnum(1143) : while compiling class template member function 'std::ostreambuf_iterator<_Elem,_Traits> std::num_put<_Elem,_OutIt>:: do_put(_OutIt,std::ios_base &,_Elem,std::_Bool) const' with [ _Elem=Tk::utf8_t, _Traits=std::char_traits<Tk::utf8_t>, _OutIt=std::ostreambuf_iterator<Tk::utf8_t,std::char_traits<Tk::utf8_t>> ] c:\program files\microsoft visual studio 10.0\vc\include\ostream(295) : see reference to class template instantiation 'std::num_put<_Elem,_OutIt>' being compiled with [ _Elem=Tk::utf8_t, _OutIt=std::ostreambuf_iterator<Tk::utf8_t,std::char_traits<Tk::utf8_t>> ] c:\program files\microsoft visual studio 10.0\vc\include\ostream(281) : while compiling class template member function 'std::basic_ostream<_Elem,_Traits> & std::basic_ostream<_Elem,_Traits>::operator <<(int)' with [ _Elem=Tk::utf8_t, _Traits=std::char_traits<Tk::utf8_t> ] c:\program files\microsoft visual studio 10.0\vc\include\sstream(526) : see reference to class template instantiation 'std::basic_ostream<_Elem,_Traits>' being compiled with [ _Elem=Tk::utf8_t, _Traits=std::char_traits<Tk::utf8_t> ] c:\users\michael\dvl\tmp\console\console.cpp(23) : see reference to class template instantiation 'std::basic_ostringstream<_Elem,_Traits,_Alloc>' being compiled with [ _Elem=Tk::utf8_t, _Traits=std::char_traits<Tk::utf8_t>, _Alloc=std::allocator<uchar> ] . c:\program files\microsoft visual studio 10.0\vc\include\xlocmon(213): error C2491: 'std::numpunct<_Elem>::id' : definition of dllimport static data member not allowed with [ _Elem=Tk::utf8_t ] Any ideas? ** Edited 19 June 2012 ** OK, I've gotten closer to understanding this, but not how to solve it. As we all know, static class variables get defined twice: once in the class definition and once outside the class definition which establishes storage space. e.g. // in .h file class CFoo { // ... static int x; }; // in .cpp file int CFoo::x = 42; Now in the VC10 headers we get something like this: template<class _Elem> class numpunct : public locale::facet { // ... _CRTIMP2_PURE static locale::id id; // ... } When the header is included in an application, _CRTIMP2_PURE is defined as __declspec(dllimport), which means that the variable is imported from a dll. Now the header also contains the following template<class _Elem> locale::id numpunct<_Elem>::id; Note the absence of the __declspec(dllimport) qualifier. i.e. The class declaration says that the static linkage of the id variable is in the dll, but for the general case, it gets declared outside the dll. For the known cases, there are specialisations. template locale::id numpunct<char>::id; template locale::id numpunct<wchar_t>::id; These are protected by #ifs so that they are only included when building the DLL. They are excluded otherwise. i.e. the char and wchar_t versions of numpunct ARE inside the dll So we have the class definition saying that id's storage is in the DLL, but that is only true for the char and wchar_t specialisations, meaning that my unsigned char version is doomed. :-( The only way forward that I can think of is to create my own specialisation: basically copying it from the header file and fixing it. This raises many issues. Anybody have a better idea?

    Read the article

  • Problem with istringstream in C++

    - by helixed
    Hello, I'm sure I'm just doing something stupid here, but I can't quite figure out what it is. When I try to run this code: #include <iostream> #include <string> #include <sstream> using namespace std; int main(int argc, char *argv[]) { string s("hello"); istringstream input(s, istringstream::in); string s2; input >> s2; cout << s; } I get this error: malloc: *** error for object 0x100016200: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug The only thing I can think of is that I allocated s2 on the stack, but I thought strings manage their own content on the heap. Any help here would be appreciated. Thanks, helixed

    Read the article

  • C++ problem with string stream istringstream

    - by user69514
    I am reading a file in the following format 1001 16000 300 12.50 2002 24000 360 10.50 3003 30000 300 9.50 where the items are: loan id, principal, months, interest rate. I'm not sure what it is that I am doing wrong with my input string stream, but I am not reading the values correctly because only the loan id is read correctly. Everything else is zero. Sorry this is a homework, but I just wanted to know if you could help me identify my error. if( inputstream.is_open() ){ /** print the results **/ cout << fixed << showpoint << setprecision(2); cout << "ID " << "\tPrincipal" << "\tDuration" << "\tInterest" << "\tPayment" <<"\tTotal Payment" << endl; cout << "---------------------------------------------------------------------------------------------" << endl; /** assign line read while we haven't reached end of file **/ string line; istringstream instream; while( inputstream >> line ){ instream.clear(); instream.str(line); /** assing values **/ instream >> loanid >> principal >> duration >> interest; /** compute monthly payment **/ double ratem = interest / 1200.0; double expm = (1.0 + ratem); payment = (ratem * pow(expm, duration) * principal) / (pow(expm, duration) - 1.0); /** computer total payment **/ totalPayment = payment * duration; /** print out calculations **/ cout << loanid << "\t$" << principal <<"\t" << duration << "mo" << "\t" << interest << "\t$" << payment << "\t$" << totalPayment << endl; } }

    Read the article

  • How to call operator<< on "this" in a descendant of std::stringstream?

    - by romkyns
    class mystream : public std::stringstream { public: void write_something() { this << "something"; } }; This results in the following two compile errors on VC++10: error C2297: '<<' : illegal, right operand has type 'const char [10]' error C2296: '<<' : illegal, left operand has type 'mystream *const ' Judging from the second one, this is because what this points at can't be changed, but the << operator does (or at least is declared as if it does). Correct? Is there some other way I can still use the << and >> operators on this?

    Read the article

1 2 3 4  | Next Page >