I'm working on Eclipse inside Ubuntu environment on my C++ project.
I use the itoa function (which works perfectly on Visual Studio) and the compiler complains that itoa is undeclared.
I included <stdio.h>, <stdlib.h>, <iostream> which doesn't help.
www.cplusplus.com says:
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
Therefore, I'd strongly suggest that you don't use it. However, you can achieve this quite straightforwardly using stringstream as follows:
stringstream ss;
ss << myInt;
string myString = ss.str();
itoa() is not part of any standard so you shouldn't use it. There's better ways, i.e...
C:
int main() {
char n_str[10];
int n = 25;
sprintf(n_str, "%d", n);
return 0;
}
C++:
using namespace std;
int main() {
ostringstream n_str;
int n = 25;
n_str << n;
return 0;
}
Boost way:
string str = boost::lexical_cast<string>(n);
itoa depends on compiler, so better use the following methods :-
method 1 :If you are using c++11, just go for std::to_string. It will do the trick.
method 2 :sprintf works for both c & c++.
ex-
ex - to_string
#include <bits/stdc++.h>
using namespace std;
int main ()
{
int i;
char buffer [100];
printf ("Enter a number: ");
scanf ("%d",&i);
string str = to_string(i);
strcpy(buffer, str.c_str());
cout << buffer << endl;
return 0;
}
Note - compile using -std=c++0x.
C++ sprintf:
int main ()
{
int i;
char buffer [100];
printf ("Enter a number: ");
scanf ("%d",&i);
sprintf(buffer, "%d", i);
return 0;
}`
you may use sprintf
char temp[5];
temp[0]="h"
temp[1]="e"
temp[2]="l"
temp[3]="l"
temp[5]='\0'
sprintf(temp+4,%d",9)
cout<<temp;
output would be :hell9
Did you include stdlib.h? (Or rather, since you're using C++, cstdlib)
Related
I am trying to get the first character of a string written to a variable of type char. With std::cin (commented out) it works fine, but with scanf() I get runtime error. It crushes when I enter "LLUUUR". Why is it so? Using MinGW.
#include <cstdio>
#include <string>
#include <iostream>
int main() {
std::string s;
scanf("%s", &s);
//std::cin >> s;
char c = s[0];
}
scanf knows nothing about std::string. If you want to read into the underlying character array you must write scanf("%s", s.data());. But do make sure that the string's underlying buffer is large enough by using std::string::resize(number)!
Generally: don't use scanf with std::string.
Another alternative if you want to use scanf and std::string
int main()
{
char myText[64];
scanf("%s", myText);
std::string newString(myText);
std::cout << newString << '\n';
return 0;
}
Construct the string after reading.
Now for the way directly on the string:
int main()
{
std::string newString;
newString.resize(100); // Or whatever size
scanf("%s", newString.data());
std::cout << newString << '\n';
return 0;
}
Although this will of course only read until the next space. So if you want to read a whole line, you would be better off with:
std::string s;
std::getline(std::cin, s);
I am trying to print the date that the user enters in a program I am working on. In this very simplified example, I am trying to get the value of an int variable inside of a string variable. Here, you can see I have tried static_cast<char>(int).
I have also tried
myStr = num;
myStr = num + 0;
myStr = num + '0';
as well as many other things that do not make sense just to see what the compiler does and what the program does - if I can get it to run.
Here's the few lines I have in this shortened example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 100;
string myStr = static_cast<char>(num);
cout << myStr;
return 0;
}
In my other program, I am trying to insert the year 2017 (saved as an int variable) into a string that contains the rest of the date. I'm just having problems with numbers bigger than 9.
Thanks for any help.
Use the standard library function std::to_string to convert your number to string form.
stringstream ss;
ss << num;
cout << ss.str();
Don't forget to include sstream
As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library and you could use to_string method.
You can use to_string to convert int to String.
#include<String>
std::string int_string = std::to_string(num);
If you have older version of c++,this will work by compiling with the flag -stdc++=11 or higher e.g
g++ filename.cpp -stdc++=11
how do i do it??
it tried this code:
char num[10];
printf("Enter num:");
scanf_s ("%s", &num);
printf("\n%s \n", num);
ignore 'num' please..
i use VS 2013, and my only included library is "stdafx.h"
See std::getline.
In C++, don't use printf, use std::cout.
Don't use char[], use std::string.
If you selected the type of the project like console application and compile it as a C++ program then the code can look the following way
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
char s[100];
std::cout << "Enter a sentence: ";
std::cin.getline( s, sizeof( s ) );
std::cout << "You entered \"" << s << "\"\n";
return 0;
}
You don't you use the "string" in c++ instead of the char array. Its easy for operation and maintenance, plus its much more simple and efficient with so many built in algorithms.
string num ;// instead of char num[10];
cout<<"Enter num";
cin>>num;
cout<<num;
you may use printf or scanf. Thats completely ok
I'm working on Eclipse, on Fedora. I want to make a number more understandable using a dot to separate the thousands. This number is an integer Value that can be 0<Value<99.999
So... if Value = 1000 it shows 1000 and what I want is to show 1.000 (note the dot). The code I need to change is the next one:
char str[12];
sprintf(str, "%d", (int)(Value));
m_Text.SetText(str);
And what I thought is to do something like:
if (Value > 999)
{
int RightPart = (int)Value % 1000;
int LeftPart = Val/1000 ;
}
And then append in a string LeftPart + "." + RightPart so if Value = 1563 it will be 1+.+563 which is 1.563
My problem is that it's very ugly to do this and I was wondering if there were a better way of doing it. I've searched on google and found imbueand localebut they are only for cout. I've see too some posts like this and this but this doesn't help me with my problem.
Thank you.
NOTE: I want to remark that I DON'T WANT to change the output format. I want to change the int I receive so I can have the dots in the str var with which I will work later.
NOTE 2: Basically the code has to: receive an integer (Value), and send it like a string to setText(). setText() will basically print it on the screen where and when it has to, and I want it to print 1.563 and not 1563 which is more difficult to read.
Use stringstream and same imbue technique for it.
For example:
struct dotted : std::numpunct<char> {
char do_thousands_sep() const { return '.'; } // separate with dots
std::string do_grouping() const { return "\3"; } // groups of 3 digits
static void imbue(std::ostream &os) {
os.imbue(std::locale(os.getloc(), new dotted));
}
};
and then:
std::stringstream ss;
dotted::imbue(ss);
ss << Value;
std::cout << ss.str();
Demo
#include <iomanip>
#include <locale>
#include <iostream>
#include <sstream>
using namespace std;
template<class T>
string format(T value)
{
stringstream ss;
ss.imbue(locale(""));
ss << fixed << value;
return ss.str();
}
int main(int argc, char argv[])
{
cout.imbue(locale(""));
cout << 1000000 << endl;
return 0;
}
Prints:
1.000.000
You should probably look at which locale is used when "" is passed and change it with a more appropriate one.
Or vice versa:
int str_to_nr(string str)
{
int val;
stringstream ss(str);
ss.imbue(locale(""));
ss >> val;
return val;
}
int main(int argc, char argv[])
{
cout << str_to_nr("1.000") << endl;
return 0;
}
Prints:
1000
#gandgandi's answer basically gives you a technique to print out the value with dots on demand using C++ streams.
sprintf (which is generally not safe to use, BTW) is a C library function. C does not provide a mechanism to alter the locale behavior in the same way C++ provides. In C, you will have to define the locale behavior with mechanisms/tools provided by your operating system and assign it a name. Then, you can use the C function setlocale to alter the locale in the program to the one you have created to get it to print how you want. However, this will only work on machines that have the locale you have created installed. It won't work on any other machine.
With only a little bit of work and almost no creative effort, you can just use the C++ solution already provided combined with a call to sprintf.
char str[12];
stringstream ss;
dotted::imbue(ss);
ss << Value;
sprintf(str, "%s", ss.str());
m_Text.SetText(str);
But, there is really no reason to use sprintf at all:
stringstream ss;
dotted::imbue(ss);
ss << Value;
m_Text.SetText(ss.str());
This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 9 years ago.
Coming from a C# background, In C# I could write this:
int int1 = 0;
double double1 = 0;
float float1 = 0;
string str = "words" + int1 + double1 + float1;
..and the casting to strings is implicit. In C++ I understand the casting has to be explicit, and I was wondering how the problem was usually tackled by a C++ programmer?
There's plenty of info on the net already I know, but there seems to quite a number of ways to do it and I was wondering if there wasn't a standard practice in place?
If you were to write that above code in C++, how would you do it?
Strings in C++ are just containers of bytes, really, so we must rely on additional functionality to do this for us.
In the olden days of C++03, we'd typically use I/O streams' built-in lexical conversion facility (via formatted input):
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::stringstream ss;
ss << "words" << int1 << double1 << float1;
std::string str = ss.str();
You can use various I/O manipulators to fine-tune the result, much as you would in a sprintf format string (which is still valid, and still seen in some C++ code).
There are other ways, that convert each argument on its own then rely on concatenating all the resulting strings. boost::lexical_cast provides this, as does C++11's to_string:
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ std::to_string(int1)
+ std::to_string(double1)
+ std::to_string(float1);
This latter approach doesn't give you any control over how the data is represented, though (demo).
std::stringstream
std::to_string
If you can use Boost.LexicalCast (available for C++98 even), then it's pretty straightforward:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main( int argc, char * argv[] )
{
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ boost::lexical_cast<std::string>(int1)
+ boost::lexical_cast<std::string>(double1)
+ boost::lexical_cast<std::string>(float1)
;
std::cout << str;
}
Live Example.
Note that as of C++11, you can also use std::to_string as mentioned by #LigthnessRacesinOrbit.
Being a C developer, I would use the C string functions, as they are perfectly valid in C++, and let you be VERY explicit with respect to the formatting of numbers (ie: integers, floating point, etc).
http://www.cplusplus.com/reference/cstdio/printf/
In the case of this, sprintf() or snprintf() is what you are looking for. The formats specifiers make it very obvious in the source code itself what your intent was as well.
The best way to cast numbers into std::string in C++ is to use what is already available.
The library sstream provide a stream implementation for std::string.
It is like using a stream ( cout, cin ) for example
Its easy to use :
http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
int main(){
stringstream ss;
string str;
int i = 10;
ss << i;
ss >> str;
cout << str << endl;
}