| | |
Beginner: Variable loses last letter upon return from function
Thread Solved |
•
•
Join Date: Aug 2009
Posts: 7
Reputation:
Solved Threads: 0
Quick background: I'm working on Project Euler and made a palindrome checker. I needed to convert integers to strings. itoa() kept giving random values (9 gave 9 or 90, etc...), so I decided to make my own, and ran into a problem. I have fixed it, but could somebody explain what caused the problem and why the fix works?
Broken Code: The below code creates a stringstream inputs the number then puts that into a string and then into a char. The problem is it would chop the last number off when returning the char. (The buffer holds the 99800 value but the receiving variable
The Fix:
Thanks.
Broken Code: The below code creates a stringstream inputs the number then puts that into a string and then into a char. The problem is it would chop the last number off when returning the char. (The buffer holds the 99800 value but the receiving variable
numaschar = strItoA(num); becomes 9980.) C++ Syntax (Toggle Plain Text)
char* strItoA(int number) { std::ostringstream sin; sin << number; std::string val = sin.str(); size_t length; char buffer[val.size()+1]; //add one for the zero terminator length=val.copy(buffer,val.length(),0); //do the transfer and grab the last position buffer[length]='\0'; //zero terminate!! return buffer; }
The Fix:
C++ Syntax (Toggle Plain Text)
char* buffer; //moved outside of function and given reference char* strItoA(int number) { //Same... buffer = new char [val.size()+1]; //added to keep buffer dynamic //char buffer[val.size()+1]; //removed //Same... }
Thanks.
Last edited by NeoFryBoy; Aug 8th, 2009 at 5:56 pm.
Curious. You should use Though Narue may tell you to generalise (which is a good idea, even though she spells it wrong
) which is where templates become your friend.
std::strings really... C++ Syntax (Toggle Plain Text)
std::string strItoA(int number) { std::ostringstream sin; sin << number; return sin.str(); }
) which is where templates become your friend. Last edited by twomers; Aug 8th, 2009 at 6:08 pm.
•
•
Join Date: Aug 2009
Posts: 7
Reputation:
Solved Threads: 0
•
•
•
•
Curious. You should usestd::strings really...Though Narue may tell you to generalise (which is a good idea, even though she spells it wrongC++ Syntax (Toggle Plain Text)
std::string strItoA(int number) { std::ostringstream sin; sin << number; return sin.str(); }) which is where templates become your friend.
That doesn't help at all. But thanks for the attempt.
•
•
•
•
Quick background: I'm working on Project Euler and made a palindrome checker. I needed to convert integers to strings. itoa() kept giving random values (9 gave 9 or 90, etc...), so I decided to make my own, and ran into a problem. I have fixed it, but could somebody explain what caused the problem and why the fix works?
Broken Code: The below code creates a stringstream inputs the number then puts that into a string and then into a char. The problem is it would chop the last number off when returning the char. (The buffer holds the 99800 value but the receiving variablenumaschar = strItoA(num);becomes 9980.)
C++ Syntax (Toggle Plain Text)
char* strItoA(int number) { std::ostringstream sin; sin << number; std::string val = sin.str(); size_t length; char buffer[val.size()+1]; //add one for the zero terminator length=val.copy(buffer,val.length(),0); //do the transfer and grab the last position buffer[length]='\0'; //zero terminate!! return buffer; }
The Fix:
C++ Syntax (Toggle Plain Text)
char* buffer; //moved outside of function and given reference char* strItoA(int number) { //Same... buffer = new char [val.size()+1]; //added to keep buffer dynamic //char buffer[val.size()+1]; //removed //Same... }
Thanks.
I think the calculation of length in line 9 is incorrect as it holds the number of characters in the array (excluding the null terminator) so changing line 10 to:
C++ Syntax (Toggle Plain Text)
buffer[val.size()]='\0';
You've already stated in your code that the buffer should be the size of val.size()+1. after copying the contents of val into the buffer, the string in the buffer will be the same size as the string in val. So the item in the buffer at the array position buffer[val.size()] must therefore be the null terminator.
Remember: You've reserved val.size()+1 spaces for buffer and in c++, arrays start at position 0. Therefore the array position at the index val.size() must be the position reserved for the null terminator!
However in your first block of code, all of that stuff copying into the char buffer strikes me as unnecessary, plus there is the scope problem. I think all you needed to do was this:
C++ Syntax (Toggle Plain Text)
char* strItoA(int number) { std::ostringstream sin; sin << number; return new std::string(sin.str()).c_str(); // The above line is equivalent to: // std::string val = new std::string(sin.str()); // return val.c_str(); // c_str() returns a c-style string (char*) from a std::string // you can also get a char* from an ostringstream // e.g. sin.str().c_str() }
Hope this is of some help.
Cheers for now,
Jas.
Last edited by JasonHippy; Aug 8th, 2009 at 6:49 pm.
Will be posting sparsely, still lots of band related stuff to do:
http://www.myspace.com/kinasis
http://www.myspace.com/kinasis
•
•
Join Date: Aug 2009
Posts: 7
Reputation:
Solved Threads: 0
Hmmm I had thought return would dump the value into a new variable before deleting the old one.
I had extended the buffer size at one point so I'm sure I wasn't overwriting.
Well, thanks for suggesting the unique usage of c_str(). I had seen it used before, but they used strcpy() along with it and I was told not to use that function.
I had extended the buffer size at one point so I'm sure I wasn't overwriting.
Well, thanks for suggesting the unique usage of c_str(). I had seen it used before, but they used strcpy() along with it and I was told not to use that function.
![]() |
Similar Threads
- Rock Paper Scissors: String Problem (C++)
- Replacing return() function (PHP)
- Is it possible to pass back both a return variable & reference variable in one funct? (C++)
- hot to get a return value from a function executed by a pthread (C)
- Trouble with a function that asks a user for a number. (C)
- return in an function (C)
- trouble with counting letter from file, please help. (C++)
- i want the user to enter an input without obligating him to press enter (C++)
- program help (C++)
Other Threads in the C++ Forum
- Previous Thread: Router log collector server
- Next Thread: HELLP me FIX this CODE.. IF-ELSE
Views: 457 | Replies: 6
| Thread Tools | Search this Thread |
Tag cloud for C++
6 algorithm array arrays assignment beginner binary c++ c++borland c/c++ calculator char class classes code compile compiler constructor conversion convert count delete dll dynamic encryption error file files filestream forms fstream function functions game givemetehcodez graph graphics gui homework iamthwee input int integer lazy link linker list loop loops map math matrix member memory network newbie number object objects opengl operator output parameter pointer pointers problem program programming project qt random read reading recursion recursive reference return server sort spoonfeeding string strings struct student studio template templates text time tree variable vc++ vector video visual win32 window windows winsock wxwidgets






