Converting int to string [duplicate] - c++

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 8 years ago.
Here str2 is a string I need to append and str1 is the string I append onto str2. After I append last to str2 I need to append a number (int cnt) to str2. So I am using the below code, which came to my mind and it is working. Is it wrong to code like this, since I saw the usage of string s = lexical_cast<string>(a); and itoa (i,buffer,10); implementations where compiler complaints about the library.
string str2;
string str1;
int cnt;
str2 += str1 ;
str2 += char(cnt+48);//cnt converted to ASCII char and appended;

This statement
str2 += char(cnt+48);
is bad. Firstly it uses magic number 48. It would be better to write at least as
str2 += char( cnt + '0' );
Secondly the code will work only if cnt contains a number with one digit.
It would be better to use standard function std::to_string For example
str2 += std::to_string( cnt );

If you don't want to use c++11 and its std::to_string(...) you can use ostringstream class.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ostringstream ss;
ss << 1;
string str = ss.str();
cout << str << endl;
return 0;
}
Output:
1

Related

Is there a built-in function that acts like strcat from the string start? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a string that I want to encircle with quotes.
What I have so far is this:
#include <stdio.h>
#include <string.h>
int main(){
char my_str[100] = {0};
strcat(my_str, "hello world!");
strcat(my_str, "\"");
strcat(strrev(my_str), "\""); // I want a simpler way for this
strrev(my_str); // and this (though it isn't that complicated...)
printf("%s", my_str);
return 0;
}
Output (as expected) is "hello world!"
Is there a simpler way, or a built-in function that does this?
PS. An answer in C++ (that handles C-strings) would be fine too
In C++, you can use the overloaded + operator for strings.
std::string my_str;
... // here you calculate the contents of my_str
my_str = "\"" + my_str + "\"";
If you are obliged to use a char array for some reason, you should convert it to a string first:
char my_str[100];
... // here you calculate the contents of my_str
auto new_my_str = "\"" + std::string(my_str) + "\"";
Here, either the first or the second string should be a C++ string (i.e. std::string and not a char array), to make the overloaded operator work.
In C++14, you can use a string literal to make the first string the correct type, using the s suffix:
char my_str[100];
... // here you calculate the contents of my_str
auto new_my_str = "\""s + my_str + "\"";
If you also want your output in the same char array, use c_str and strcpy on the resulting C++ string. You can even fit it into one line of code:
char my_str[100];
... // here you calculate the contents of my_str
strcpy(my_str, ("\""s + my_str + "\"").c_str());
This code is vulnerable to buffer overflow, unlike all the previous ones.
I suppose that the source array already contains a string. Otherwise you could build the string in quotes very easy from scratch.
Here you are.
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[100] = "Hello World";
size_t n = strlen( s );
memmove( s + 1, s, n );
s[0] = '\"';
s[n+1] = '\"';
s[n+2] = '\0';
puts( s );
return 0;
}
The program output is
"Hello World"
In C++ if to use the template class std::string then the same task can be done the following way
#include <iostream>
#include <string>
int main()
{
std::string s( "Hello World" );
s.reserve( s.size() + 2 );
s.insert( 0, 1, '\"' );
s += '\"';
std::cout << s << std::endl;
return 0;
}
Otherwise if you deal with a character array that contains a string then the approach will be the same as it is shown for C.
This is quite simple. Just start with a string that holds the opening quote:
char my_str[100] = "\"";
strcat(my_str, "Hello, world!");
strcat(my_str, "\"");
Or, if you don't want to initialize the string that way, just copy the opening quote:
char my_str[100];
strcpy(my_str, "\"");
strcat(my_str, "Hello, world!");
strcat(my_str, "\"");
Is there a built-in function that acts like strcat from the string start?
Yes, it is called strcat. What you would do in the normal case, is simply to create a second string:
char arr1[N] = "hello world";
char* use_this = arr1;
puts(use_this);
char arr2[N] = "\"";
strcat(arr2, use_this);
use_this = arr2;
strcat(use_this "\"");
puts(use_this);
Trying to be "smart" and save memory by doing this in-place is probably not a good idea, since it comes at the expense of execution speed.
As a side note, your code won't compile on a standard C compiler, because there is no function called "strrev" in the C language. It is a non-standard extension and should therefore be avoided.
There is an easier way - just shift the existing string the required amount of space to make room for the string you want to prepend. Since the source and target areas of memory are overlapping you can't use strcpy or memcpy, but instead have to use memmove
memmove(my_str+1,my_str,strlen(my_str)+1);
and then replace the first character with the double quote.
my_str[0]='\"';

c++ paste value and print string

I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.
Here is my code
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
string s,s1;
cin>>s;
s1[0]=s[1];
s1[1]=s[2];
s1[2]=s[3];
s1[3]='\0';
cout<<s1<<endl;
return 0;
}
s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?
Probably, the easiest way to accomplish OP's task is to use a library function like substr() which takes care of all the details the posted code is missing (and already pointed out):
memory management. The second string s1 is empty, so trying to write its first four (unallocated) elements is undefined behavior. In general, s1 should be resized to the needed length.
null terminator. A std::string can manage it's internal representation and always returns a null-terminated string via its member functions c_str and data (since C++11).
That's how it could be done:
#include <iostream>
#include <string>
int main()
{
std::string s;
std::cin >> s;
std::string s1;
std::string::size_type start_pos = 1,
count = 3;
if ( s.size() > start_pos )
s1 = s.substr(start_pos, count);
std::cout << s1 << '\n';
}
s1 doesn't have any characters. You're trying to change the value of characters that do not exist.
Your program has undefined behaviour, and might just as easily open a llama zoo, reverse the polarity of the Earth's magnetic field, or solve cold fusion in the bath.
Make s1 the correct size before writing things to it;
Don't write a '\0' to the end; this is not a C string; that is unnecessary. C++ strings look after themselves.
Here's an example:
#include <iostream>
#include <cassert>
int main()
{
std::string s, s1;
std::cin >> s;
assert(s.size() >= 4);
s1.resize(3);
s1[0] = s[1];
s1[1] = s[2];
s1[2] = s[3];
std::cout << s1 << std::endl;
}
live demo
You can not assign as s1[0] = s[1]
Correct way is using assign function as:
string s,s1;
cin>>s;
s1.assign(s.begin()+1,s.begin()+4);
cout<<s1<<endl;
String assignment cannot be done by assigning indexes without fixing or defining the size of the string. It may cause a string subscript error. If you want to do this, I think string concatenation is the best method; that is, by adding substrings or string indexes into string. I've given some code below that uses the string concatenation method.
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
string s,s1="";
cin>>s;
s1= s1 + s[1];
s1= s1 + s[2];
s1= s1 + s[3];
cout<<s1<<endl;
return 0;
}

C++ : writing to specific index position in std::string

Hi I am new to community.
I have a question regarding std::string.
Is it possible to write into specific index of string keeping rest of string empty ?
e.g.
std::string tempString = "";
tempString ->insert(10, "Some String I want to Insert");
//index position and string to insert
and final answer would be tempString = "__________Some String I want to Insert"
where characters 0 through 9 are uninitialized.
this is possible with char * once memory is allocated.
but is this possible with std::strings ?
Thank you in advance and thank you for having me in this community :)
Given some insertion position
size_t insertion_position = 10;
And some std::string or const char* to be inserted
const char *text = "Some String I want to Insert";
This will do it efficiently.
std::string tempString( insertion_position, ' ' );
tempString += text;
Or as a one liner:
std::string tempString = std::string( insertion_position, ' ' ) + text;
check this out, you may be able to use a stringstream instead of cout. Then you can just get the output into a string instead of seeing it dumped on the console
// using the fill character
#include <iostream> // std::cout
int main () {
char prev;
std::cout.width (10);
std::cout << 40 << '\n';
prev = std::cout.fill ('x');
std::cout.width (10);
std::cout << 40 << '\n';
std::cout.fill(prev);
return 0;
}
Output:
40
xxxxxxxx40
Is it possible to write into specific index of string keeping rest of string [uninitialized] ?
No.
std::basic_string is not designed to represent collections of uninitialized values.

C++ int to string, concatenate strings [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 8 years ago.
I'm new to C++ and working on a simple project. Basically where I'm encountering a problem is creating a file with a number (int) in the file name. As I see it,I have to first convert the int to a string (or char array) and then concatenate this new string with the rest of the file name.
Here is my code so far that fails to compile:
int n; //int to include in filename
char buffer [33];
itoa(n, buffer, 10);
string nStr = string(buffer);
ofstream resultsFile;
resultsFile.open(string("File - ") + nStr + string(".txt"));
This gives a couple compilation errors (compiling in Linux):
itoa not declared in this scope
no matching function for call to ‘std::basic_ofstream char, std::char_traits char ::open(std::basic_string char, std::char_traits char , std::allocator char )’
I've tried the advice here: c string and int concatenation
and here: Easiest way to convert int to string in C++ with no luck.
If I using the to_string method, I end up with the error "to_string not a member of std".
You could use a stringstream to construct the filename.
std::ostringstream filename;
filename << "File - " << n << ".txt";
resultsFile.open(filename.str().c_str());
For itoa, you are likely missing #include <stdlib.h>. Note that itoa is non-standard: the standard ways to format an integer as string as sprintf and std::ostringstream.
ofstream.open() takes a const char*, not std::string. Use .c_str() method to obtain the former from the latter.
Putting it together, you are looking for something like this:
ostringstream nameStream;
nameStream << "File - " << n << ".txt";
ofstream resultsFile(nameStream.str().c_str());
You want to use boost::lexical_cast. You also need to include any needed headers:
#include <boost/lexical_cast>
#include <string>
std::string nStr = boost::lexical_cast<std::string>(n);
then it's simply:
std::string file_name = "File-" + nStr + ".txt";
because std::strng plays nicely with string literals (e.g. ".txt").
Using std::ostringstream:
std::ostringstream os;
os << "File - " << nStr << ".txt";
std::ofstream resultsFile(os.str().c_str());
Using std::to_string (C++11):
std::string filename = "File - " + std::to_string(nStr) + ".txt";
std::ofstream resultsFile(filename.c_str());
for itoa function
include <stdlib.h>
consider this link
http://www.cplusplus.com/reference/cstdlib/itoa/
You can use std::stringstream
std::stringstream ss;
ss << "File - " << n << ".txt";
Since the constructor requires a char pointer, you need to convert it into a char pointer using
ofstream resultsFile(ss.str().c_str());

Find length of string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ String Length?
I really need a help now. How to accept string as input and find the length of the string? I just want a simple code just to know how it works. Thanks.
Hint:
std::string str;
std::cin >> str;
std::cout << str.length();
in c++:
#include <iostream>
#include <string>
std::string s;
std::cin >> s;
int len = s.length();
You can use strlen(mystring) from <string.h>. It returns the length of a string.
Remember: A string in C is an array of chars which ends in character '\0'. Providing enough memory is reserved (the whole string + 1 byte fits on the array), the length of the string will be the number of bytes from the pointer (mystring[0]) to the character before '\0'
#include <string.h> //for strlen(mystring)
#include <stdio.h> //for gets(mystring)
char mystring[6];
mystring[0] = 'h';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';
strlen(mystring); //returns 5, current string pointed by mystring: "hello"
mystring[2] = '\0';
strlen(mystring); //returns 2, current string pointed by mystring: "he"
gets(mystring); //gets string from stdin: http://www.cplusplus.com/reference/clibrary/cstdio/gets/
http://www.cplusplus.com/reference/clibrary/cstring/strlen/
EDIT: As noted in the comments, in C++ it's preferable to refer to string.h as cstring, therefore coding #include <cstring> instead of #include <string.h>.
On the other hand, in C++ you can also use C++ specific string library which provides a string class which allows you to work with strings as objects:
http://www.cplusplus.com/reference/string/string/
You have a pretty good example of string input here: http://www.cplusplus.com/reference/string/operator%3E%3E/
In this case you can declare a string and get its length the following way:
#include <iostream>
#include <string>
string mystring ("hello"); //declares a string object, passing its initial value "hello" to its constructor
cout << mystring.length(); //outputs 5, the length of the string mystring
cin >> mystring; //reads a string from standard input. See http://www.cplusplus.com/reference/string/operator%3E%3E/
cout << mystring.length(); //outputs the new length of the string