concatenate char with int - c++

I have to concatenate char with int.
Here's my code:
int count = 100;
char* name = NULL;
sprintf((char *)name, "test_%d", count);
printf("%s\n", name);
Nothing printed. What's the problem?

You didn't allocate any memory into which sprintf could copy its result. You might try:
int count = 100;
char name[20];
sprintf(name, "test_%d", count);
printf("%s\n", name);
Or even:
int count = 100;
char *name = malloc(20);
sprintf(name, "test_%d", count);
printf("%s\n", name);
Of course, if your only goal is the print the combined string, you can just do this:
printf("test_%d\n", 100);

If you programm C++ use sstream instead:
stringstream oss;
string str;
int count =100
oss << count;
str=oss.str();
cout << str;

You have to allocate memory for name first. In C, library functions like sprintf won't make it for you.
In fact, I am very surprised that you didn't get a segmentation fault.
A simple workaround would be using char name[5+11+1] for the case of 32-bit int.

I use boost::format for this.
#include <boost/format.hpp>
int count = 100;
std::string name = boost::str( boost::format("test_%1%") % count );

Since the answer is tagged C++, this is probably how you should do it there:
The C++11 way: std::string str = "Hello " + std::to_string(5);
The Boost way: std::string str = "Hello " + boost::lexical_cast<std::string>(5);

#include <iostream>
#include <string>
#include <sstream>
int count = 100;
std::stringstream ss;
ss << "Helloworld";
ss << " ";
ss << count ;
ss << std::endl;
std::string str = ss.str();
std::cout << str;
const char * mystring = str.c_str();

Related

How to concatenate strings in an output function?

Some languages have easy ways of doing this, but my question revolves in C and C++.
I wanna do something like this in Java:
public class sandbox {
public static void main(String[] args) {
System.out.println("Thank" + " you!");
}
}
And transfer it in C:
#include <stdio.h>
int main() {
/* The easiest way is like this:
char *text1 = "Thank";
char *text2 = " you";
printf("%s%s\n", text1, text2);
*/
printf("Thank" + " you."); // What I really want to do
}
How do I concatenate strings in a language like this?
You use just nothing:
puts ("Thank" " you.");
Concatenating strings is not that easy in C unfortunately, here's how to do it most succinctly:
char *text1 = "Thank";
char *text2 = " you";
char *text_concat = malloc(strlen(text1) + strlen(text2) + 1);
assert(text_concat);
text_concat = strcpy(text_concat, text1);
text_concat = strcat(text_concat, text2);
printf("%s\n", text_concat);
free(text_concat);
What I have understood from your question, hope the below solution will answer your question.
#include <stdio.h>
int main() {
char s1[100] = "Thank ", s2[] = "You";
int length, j;
// store length of s1 in the length variable
length = 0;
while (s1[length] != '\0') {
++length;
}
// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j];
}
// terminating the s1 string
s1[length] = '\0';
printf("After concatenation: %s",s1);
return 0;
}
In C++, you can easily concatenate two string it by adding two string with a + operator.
#include <iostream>
using namespace std;
int main()
{
string s1, s2, result;
cout << "Enter string s1: ";
cin>>s1;
cout << "Enter string s2: ";
cin>>s2;
result = s1 + s2;
cout << "After concatenation: = "<< result;
return 0;
}
This is a concatenation, but is a constant or compile time concatenation, you can't concatenate strings like that, but in case you need to split a string constant in multiple parts is ok:
...
printf("Thank" " you."); // What I really want to do
...
For dynamic, runtime concatenation you need strcat like
strcat(text1, text2);
First you must assure that you have enough memory in target string, see this link http://www.cplusplus.com/reference/cstring/strcat/
Ok, that was the C way, but C++ has STL with std::string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "hello ", str2 = "world";
cout<< str1 + str2<< endl;
return 0;
}
It is not possible in C to do something like printf("Thank" + " you."); because C doesn't support Operator Overloading Unlike C++. You can refer Is it possible to overload operators in C?

C++: Converting stringstream to char* runtime error

I am trying to convert in C++ a stringstream of "1.txt" so that it is equal to a char* value of "1.txt". I need the raw char* as an argument for a function, so it can't be const char or anything else. When I run it, I get a blank output. Why, and how do I fix it?
#define SSTR(x) dynamic_cast< std::stringstream & >( (std::stringstream() << std::dec << x ) ).str()
int booknum = 1;
std::stringstream stringstream;
stringstream << SSTR(booknum) << ".txt";
std::vector<std::string> argv;
std::vector<char*> argc;
std::string arg;
std::string arg3;
while (stringstream >> arg) argv.push_back(arg);
for (auto i = argv.begin(); i != argv.end(); i++)
argc.push_back(const_cast<char*>(i->c_str()));
argc.push_back(0);
int arg4 = argc.size();
for (int i = 0; i < arg4; i++)
std::cout << &arg3[i] << std::endl;
That seems very complicated, instead of e.g.
std::ostringstream oss;
oss << booknum << ".txt";
std::string s = oss.str();
char* pString = new char[s.length() + 1];
std::copy(s.c_str(), s.c_str() + s.length() + 1, pString);
yourFunctionThatTakesCharPtr(pString);
delete[] pString;
Here's a sample conversion code:
#include <iostream>
#include <sstream>
#include <typeinfo> //it's just to print the resultant type to be sure
int main() {int booknum=1;
std::stringstream ss;
ss << booknum<<"1.txt";
char* x=new char[ss.str().length()+1];
ss >> x;
std::cout<<typeid(x).name();
return 0;}
Output:
Pc

What is the proper way to create a temporary char* and print to it?

I have a helper function that takes an unsigned char array of a fixed length, and returns it as a formatted char *. However, I'm having some problems.
I tried
char* byteArrayToString(unsigned char byte[6]) {
char t[18] = {""};
char* str = t;
sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
return str;
}
and
char* byteArrayToString(unsigned char byte[6]) {
std::string t = "";
char* str = t;
sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
return str;
}
and
char* byteArrayToString(unsigned char byte[6]) {
char* str = new char();
sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
return str;
}
The second one results in some side effects of the value of that string being changed. The first one ends up giving me junk values and the last seg faults (but I can't figure out why).
The problem with your first one is not in the printing, but in the returning. You're returning a pointer to an array which has been reclaimed (because it is an automatic variable, its lifetime ends when the function returns).
Instead try:
string byteArrayToString(const unsigned char* const byte)
{
char t[18] = {""};
sprintf(t, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
return t;
}
Proper way is to return std::string as:
#include <sstream> //for std::ostringstream
#include <string> //for std::string
#include <iomanip> //for std::setw, std::setfill
std::string byteArrayToString(unsigned char byte[6])
{
std::ostringstream ss;
for(size_t i = 0 ; i < 5 ; ++i)
ss << "0X" << std::hex << std::setw(2) << std::setfill('0') << (int) byte[i] << ":";
ss << "0X" << std::hex << std::setw(2) << std::setfill('0') << (int) byte[5];
return ss.str();
}
Online demo
On the callsite you can get const char* as:
std::string s = byteArrayToString(bytes);
const char *str = s.c_str();

converting from strings to ints

I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it.
Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf'
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
EDIT 2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
Like wise, the following is to convert number to string.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
Use atoi to convert a string to an int. Use a stringstream to convert the other way.

how do i add a int to a string

i have a string and i need to add a number to it i.e a int. like:
string number1 = ("dfg");
int number2 = 123;
number1 += number2;
this is my code:
name = root_enter; // pull name from another string.
size_t sz;
sz = name.size(); //find the size of the string.
name.resize (sz + 5, account); // add the account number.
cout << name; //test the string.
this works... somewhat but i only get the "*name*88888" and... i don't know why.
i just need a way to add the value of a int to the end of a string
There are no in-built operators that do this. You can write your own function, overload an operator+ for a string and an int. If you use a custom function, try using a stringstream:
string addi2str(string const& instr, int v) {
stringstream s(instr);
s << v;
return s.str();
}
Use a stringstream.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int a = 30;
stringstream ss(stringstream::in | stringstream::out);
ss << "hello world";
ss << '\n';
ss << a;
cout << ss.str() << '\n';
return 0;
}
You can use string streams:
template<class T>
std::string to_string(const T& t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
// usage:
std::string s("foo");
s.append(to_string(12345));
Alternatively you can use utilities like Boosts lexical_cast():
s.append(boost::lexical_cast<std::string>(12345));
Use a stringstream.
int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
you can use lexecal_cast from boost, then C itoa and of course stringstream from STL