How to convert? C-string format of toString() [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need a c-string format of toString(), but how do I convert it? Here is the function:
string toString(){
string tmp;
char buf[80];
if (*d != 1)
sprintf_s(buf, "%d/%d", *n, *d);
else sprintf_s(buf, "%d", *n);
tmp = string(buf);
return tmp;
}

need a c-string format of toString()
If you just need to convert the output of toString(), you can use
const char* s = toString().c_str();
Your function currently is returning a string (I'm guessing your code has using namespace std) which means a C++ string object.
If you don't absolutely need C strings, I would recommend using C++ strings, since they are more current and just easier to work with. However, if for reasons somewhere else in the code you do need a C string, your function should look like
char* toString() {
// formatting your output
}
Because all a C string is is a null terminated ('\0') array of char, and an array is equivalent to a pointer to the first element, so that's where char* comes from.
In either case, C++ stringstreams will make formatting your output far more intuitive. You will need #include <sstream> and then some googling will steer you in the right direction. This solution also works if you need a C string, because C++ strings have a method called c_str() that converts C++ strings into C strings (null terminated array of characters):
#include <string>
#include <sstream>
using namespace std;
char* toString() {
stringstream ss; // these are so useful!
if (*d != 1) {
// this probably isn't the exact formatting you are looking for,
// but stringstreams can certainly do it if you research a bit!
ss << *n << *d;
}
else {
ss << *n;
}
string output = ss.str();
return output.c_str();
}

Related

Extracting and Creating separate txt files for each line of the source file [duplicate]

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 7 years ago.
I was wondering if there was an alternative to itoa() for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use std::to_string:
#include <string>
std::string s = std::to_string(5);
If you're working with prior to C++11, you could use C++ streams:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
boost::lexical_cast works pretty well.
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
std::string foo = boost::lexical_cast<std::string>(argc);
}
Archeology
itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
The C Way
Use sprintf. Or snprintf. Or whatever tool you find.
Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).
The C++ way.
Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).
Conclusion
You're in C++, which means that you can choose the way you want it:
The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.
The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).
Try sprintf():
char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"
sprintf() is like printf() but outputs to a string.
Also, as Parappa mentioned in the comments, you might want to use snprintf() to stop a buffer overflow from occuring (where the number you're converting doesn't fit the size of your string.) It works like this:
snprintf(str, sizeof(str), "%d", num);
Behind the scenes, lexical_cast does this:
std::stringstream str;
str << myint;
std::string result;
str >> result;
If you don't want to "drag in" boost for this, then using the above is a good solution.
We can define our own iota function in c++ as:
string itoa(int a)
{
string ss=""; //create empty string
while(a)
{
int x=a%10;
a/=10;
char i='0';
i=i+x;
ss=i+ss; //append new character at the front of the string!
}
return ss;
}
Don't forget to #include <string>.
С++11 finally resolves this providing std::to_string.
Also boost::lexical_cast is handy tool for older compilers.
I use these templates
template <typename T> string toStr(T tmp)
{
ostringstream out;
out << tmp;
return out.str();
}
template <typename T> T strTo(string tmp)
{
T output;
istringstream in(tmp);
in >> output;
return output;
}
Try Boost.Format or FastFormat, both high-quality C++ libraries:
int i = 10;
std::string result;
WIth Boost.Format
result = str(boost::format("%1%", i));
or FastFormat
fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);
Obviously they both do a lot more than a simple conversion of a single integer
You can actually convert anything to a string with one cleverly written template function. This code example uses a loop to create subdirectories in a Win-32 system. The string concatenation operator, operator+, is used to concatenate a root with a suffix to generate directory names. The suffix is created by converting the loop control variable, i, to a C++ string, using the template function, and concatenating that with another string.
//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>
using namespace std;
string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an */
/* integer as input and as output, */
/* returns a C++ string. */
/* itoa() returned a C-string (null- */
/* terminated) */
/* This function is not needed because*/
/* the following template function */
/* does it all */
/**************************************/
string r;
stringstream s;
s << x;
r = s.str();
return r;
}
template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of */
/* C++ templates. This function will */
/* convert anything to a string! */
/* Precondition: */
/* operator<< is defined for type T */
/**************************************/
string r;
stringstream s;
s << argument;
r = s.str();
return r;
}
int main( )
{
string s;
cout << "What directory would you like me to make?";
cin >> s;
try
{
mkdir(s.c_str());
}
catch (exception& e)
{
cerr << e.what( ) << endl;
}
chdir(s.c_str());
//Using a loop and string concatenation to make several sub-directories
for(int i = 0; i < 10; i++)
{
s = "Dir_";
s = s + toString(i);
mkdir(s.c_str());
}
system("PAUSE");
return EXIT_SUCCESS;
}
Allocate a string of sufficient length, then use snprintf.
int number = 123;
stringstream = s;
s << number;
cout << ss.str() << endl;
I wrote this thread-safe function some time ago, and am very happy with the results and feel the algorithm is lightweight and lean, with performance that is about 3X the standard MSVC _itoa() function.
Here's the link. Optimal Base-10 only itoa() function? Performance is at least 10X that of sprintf(). The benchmark is also the function's QA test, as follows.
start = clock();
for (int i = LONG_MIN; i < LONG_MAX; i++) {
if (i != atoi(_i32toa(buff, (int32_t)i))) {
printf("\nError for %i", i);
}
if (!i) printf("\nAt zero");
}
printf("\nElapsed time was %f milliseconds", (double)clock() - (double)(start));
There are some silly suggestions made about using the caller's storage that would leave the result floating somewhere in a buffer in the caller's address space. Ignore them. The code I listed works perfectly, as the benchmark/QA code demonstrates.
I believe this code is lean enough to use in an embedded environment. YMMV, of course.
The best answer, IMO, is the function provided here:
http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
It mimics the non-ANSI function provided by many libs.
char* itoa(int value, char* result, int base);
It's also lightning fast and optimizes well under -O3, and the reason you're not using c++ string_format() ... or sprintf is that they are too slow, right?
If you are interested in fast as well as safe integer to string conversion method and not limited to the standard library, I can recommend the format_int method from the {fmt} library:
fmt::format_int(42).str(); // convert to std::string
fmt::format_int(42).c_str(); // convert and get as a C string
// (mind the lifetime, same as std::string::c_str())
According to the integer to string conversion benchmarks from Boost Karma, this method several times faster than glibc's sprintf or std::stringstream. It is even faster than Boost Karma's own int_generator as was confirm by an independent benchmark.
Disclaimer: I'm the author of this library.
Note that all of the stringstream methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...
See here for more. Convert a number to a string with specified length in C++
On Windows CE derived platforms, there are no iostreams by default. The way to go there is preferaby with the _itoa<> family, usually _itow<> (since most string stuff are Unicode there anyway).
Most of the above suggestions technically aren't C++, they're C solutions.
Look into the use of std::stringstream.

Convert C program to C++ [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Help! I'm trying to figure out this code our professor gave us -
#include <stdio.h>
#include <string.h>
void encrypt(int offset, char *str) {
int i,l;
l=strlen(str);
printf("\nUnencrypted str = \n%s\n", str);
for(i=0;i<l;i++)
if (str[i]!=32)
str[i] = str[i]+ offset;
printf("\nEncrypted str = \n%s \nlength = %d\n", str, l);
}
void decrypt(int offset, char *str) {
// add your code here
}
void main(void) {
char str[1024];
printf ("Please enter a line of text, max %d characters\n", sizeof(str));
if (fgets(str, sizeof(str), stdin) != NULL)
{
encrypt(5, str); // What is the value of str after calling "encrypt"?
// add your method call here:
}
}
We are suppose to do the following:
Convert the C code to C++.
Add codes to the "decrypt" method to decipher the encrypted text.
Change the code to use pointer operations instead of array operations to encrypt and decrypt messages.
In the main method, call the "decrypt" method to decipher the encrypted text (str).
This is as far as I managed to go, but I'm pretty much stuck now. Especially since I have no background in the C language. Any help would be appreciated.
#include <iostream>
#include <string.h>
void encrypt(int offset, char *str)
{
std::cout << "\nUnencrypted str = \n" << str;
char *pointer = str;
while(*pointer)
{
if (*pointer !=32)
*pointer = *pointer + offset;
++pointer;
}
std::cout <<"\nEncrypted str =\n" << str << "\n\nlength = ";
}
void decrypt(int offset, char *str) {
// add your code here
}
void main(void) {
char str[1024];
std::cout << "Please enter a line of text max " << sizeof(str) << " characters\n";
if (fgets(str, sizeof(str), stdin) != NULL)
{
encrypt(5, str); // What is the value of str after calling "encrypt"?
// add your method call here:
}
}
The code you posted should work in C++ as well as C. There shouldn't be a need to "convert" anything, unless there are specific requirements that you haven't told us about.
Your array-to-pointer conversion looks correct, although I would argue that the code is more readable in the array form.
For your decrypt method, you will want to write code that does the inverse of what the encrypt method does. The best way to approach this is to run some sample text through encrypt and examine what the output looks like. The function transforms the input a single character at a time, so you should be able to map input to output on a byte-by-byte basis. With this information, you can detect the pattern and construct a function that makes the transformation in the other direction.
Most well formed C code is compilable as C++, rename the file .cpp, compile the code using C++ compilation and fix what breaks. The declaration of main() as returning void at least should break (it is at best questionable C code, and explicitly incorrect C++).
It all really depends on what your professor expects from you; the requirement to "convert it to C++" is too vague. What features of C++ are you expected to use?. While simple recompilation as C++ technically makes it C++ code (even if it is also valid C code), I somehow doubt that was the intention of the exercise.
The point is that while a superficial conversion by recompilation is possible, C++ offers opportunities for coding it differently. For example:
The header file names <stdio.h> and <string.h> are deprecated in C++, you might use <cstdio> and <cstring> instead. That said in this code <string.h> is redundant; none of the code is dependent on it.
If you use the non-deprecated headers, all the standard library is then in the std:: namespace, so all standard library symbols require scope resolution by prefixing them std:: or (less favourably) by using a using namespace std' directive.
The code uses the C standard library, which is also part of the C++ standard library, but C++ has alternatives that are in many ways superior. <cstdio> for example is largely replaced by <iostream> and its derivatives such as <stringstream> and <fstream>, and string handling and in fact a string data type is provided by <string>. The use <iostream> and <string> to implement this code could drastically simplify it.
If you were to use the std::string class, you might then use iterators to traverse the string content.
C++ supports OOP. In this case you might create a class that contains both encrypt and decrypt methods for example. Although the argument for doing so in this case is possibly weak other than perhaps to exemplify your understanding of the concept.
So you see the scope for "conversion" is very broad, from next to no work to a complete redesign. On the design note, one thing I would do is separate the encrypt/decrypt methods from the output operation. These methods would be reusable if they did not insist on outputting their results to the console. They would do better to return the data to the caller where the caller could do what it needed with it. Of course that too may be beyond the scope of this exercise is that is how the assignment were presented to you.

How to use strtok() using a string argumnet instead of character array? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Using strtok with a string argument (instead of char*)?
When using strtok() i do the following
char str[300];
while(infile) {
infile.getline(str,300);
char* token=strtok(str," ");
How can i use a string instead of the character array char str[300];
is there a way to use it to be like this,string str;
while(infile) {
infile.getline(str,300);
char* token=strtok(str," ");
I don't think you can, at least not without great care; strtok() modifies its argument, writing a \0 into it after every recognized token, and generally behaves like a function that's poorly behaved even for C, much less C++. My advice would be to look for a native C++ solution instead.
If you mean an std::string, you cannot, strtok only works with char*.
An easy solution could be that of strdup your string.c_str, and pass it to strtok.
string str;
while(infile)
{
getline(infile, str);
char* token=strtok(&str[0], " ");
}
Clean it ain't, but it will work.
EDIT: My mistake, this may not work in all circumstances.

Alternative to itoa() for converting integer to string C++? [duplicate]

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 7 years ago.
I was wondering if there was an alternative to itoa() for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use std::to_string:
#include <string>
std::string s = std::to_string(5);
If you're working with prior to C++11, you could use C++ streams:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
boost::lexical_cast works pretty well.
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
std::string foo = boost::lexical_cast<std::string>(argc);
}
Archeology
itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
The C Way
Use sprintf. Or snprintf. Or whatever tool you find.
Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).
The C++ way.
Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).
Conclusion
You're in C++, which means that you can choose the way you want it:
The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.
The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).
Try sprintf():
char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"
sprintf() is like printf() but outputs to a string.
Also, as Parappa mentioned in the comments, you might want to use snprintf() to stop a buffer overflow from occuring (where the number you're converting doesn't fit the size of your string.) It works like this:
snprintf(str, sizeof(str), "%d", num);
Behind the scenes, lexical_cast does this:
std::stringstream str;
str << myint;
std::string result;
str >> result;
If you don't want to "drag in" boost for this, then using the above is a good solution.
We can define our own iota function in c++ as:
string itoa(int a)
{
string ss=""; //create empty string
while(a)
{
int x=a%10;
a/=10;
char i='0';
i=i+x;
ss=i+ss; //append new character at the front of the string!
}
return ss;
}
Don't forget to #include <string>.
С++11 finally resolves this providing std::to_string.
Also boost::lexical_cast is handy tool for older compilers.
I use these templates
template <typename T> string toStr(T tmp)
{
ostringstream out;
out << tmp;
return out.str();
}
template <typename T> T strTo(string tmp)
{
T output;
istringstream in(tmp);
in >> output;
return output;
}
Try Boost.Format or FastFormat, both high-quality C++ libraries:
int i = 10;
std::string result;
WIth Boost.Format
result = str(boost::format("%1%", i));
or FastFormat
fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);
Obviously they both do a lot more than a simple conversion of a single integer
You can actually convert anything to a string with one cleverly written template function. This code example uses a loop to create subdirectories in a Win-32 system. The string concatenation operator, operator+, is used to concatenate a root with a suffix to generate directory names. The suffix is created by converting the loop control variable, i, to a C++ string, using the template function, and concatenating that with another string.
//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>
using namespace std;
string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an */
/* integer as input and as output, */
/* returns a C++ string. */
/* itoa() returned a C-string (null- */
/* terminated) */
/* This function is not needed because*/
/* the following template function */
/* does it all */
/**************************************/
string r;
stringstream s;
s << x;
r = s.str();
return r;
}
template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of */
/* C++ templates. This function will */
/* convert anything to a string! */
/* Precondition: */
/* operator<< is defined for type T */
/**************************************/
string r;
stringstream s;
s << argument;
r = s.str();
return r;
}
int main( )
{
string s;
cout << "What directory would you like me to make?";
cin >> s;
try
{
mkdir(s.c_str());
}
catch (exception& e)
{
cerr << e.what( ) << endl;
}
chdir(s.c_str());
//Using a loop and string concatenation to make several sub-directories
for(int i = 0; i < 10; i++)
{
s = "Dir_";
s = s + toString(i);
mkdir(s.c_str());
}
system("PAUSE");
return EXIT_SUCCESS;
}
Allocate a string of sufficient length, then use snprintf.
int number = 123;
stringstream = s;
s << number;
cout << ss.str() << endl;
I wrote this thread-safe function some time ago, and am very happy with the results and feel the algorithm is lightweight and lean, with performance that is about 3X the standard MSVC _itoa() function.
Here's the link. Optimal Base-10 only itoa() function? Performance is at least 10X that of sprintf(). The benchmark is also the function's QA test, as follows.
start = clock();
for (int i = LONG_MIN; i < LONG_MAX; i++) {
if (i != atoi(_i32toa(buff, (int32_t)i))) {
printf("\nError for %i", i);
}
if (!i) printf("\nAt zero");
}
printf("\nElapsed time was %f milliseconds", (double)clock() - (double)(start));
There are some silly suggestions made about using the caller's storage that would leave the result floating somewhere in a buffer in the caller's address space. Ignore them. The code I listed works perfectly, as the benchmark/QA code demonstrates.
I believe this code is lean enough to use in an embedded environment. YMMV, of course.
The best answer, IMO, is the function provided here:
http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
It mimics the non-ANSI function provided by many libs.
char* itoa(int value, char* result, int base);
It's also lightning fast and optimizes well under -O3, and the reason you're not using c++ string_format() ... or sprintf is that they are too slow, right?
If you are interested in fast as well as safe integer to string conversion method and not limited to the standard library, I can recommend the format_int method from the {fmt} library:
fmt::format_int(42).str(); // convert to std::string
fmt::format_int(42).c_str(); // convert and get as a C string
// (mind the lifetime, same as std::string::c_str())
According to the integer to string conversion benchmarks from Boost Karma, this method several times faster than glibc's sprintf or std::stringstream. It is even faster than Boost Karma's own int_generator as was confirm by an independent benchmark.
Disclaimer: I'm the author of this library.
Note that all of the stringstream methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...
See here for more. Convert a number to a string with specified length in C++
On Windows CE derived platforms, there are no iostreams by default. The way to go there is preferaby with the _itoa<> family, usually _itow<> (since most string stuff are Unicode there anyway).
Most of the above suggestions technically aren't C++, they're C solutions.
Look into the use of std::stringstream.

How do you convert a C++ string to an int? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse a string to an int in C++?
How do you convert a C++ string to an int?
Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).
Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.
#include <sstream>
// st is input string
int result;
stringstream(st) >> result;
Use the C++ streams.
std::string plop("123");
std::stringstream str(plop);
int x;
str >> x;
/* Lets not forget to error checking */
if (!str)
{
// The conversion failed.
// Need to do something here.
// Maybe throw an exception
}
PS. This basic principle is how the boost library lexical_cast<> works.
My favorite method is the boost lexical_cast<>
#include <boost/lexical_cast.hpp>
int x = boost::lexical_cast<int>("123");
It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).
I have used something like the following in C++ code before:
#include <sstream>
int main()
{
char* str = "1234";
std::stringstream s_str( str );
int i;
s_str >> i;
}
C++ FAQ Lite
[39.2] How do I convert a std::string to a number?
https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num
Let me add my vote for boost::lexical_cast
#include <boost/lexical_cast.hpp>
int val = boost::lexical_cast<int>(strval) ;
It throws bad_lexical_cast on error.
Use atoi
Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.
Am I just missing the point here?
in "stdapi.h"
StrToInt
This function tells you the result, and how many characters participated in the conversion.