c++ paste value and print string - c++

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;
}

Related

String assignment by each element

I wrote a string assignment in c++, but I don't know why it output s[0], while output none of s?
The code is following, and the output is: h**hello*
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
s[0] = 'h';
s[1] = 'i';
string s2;
s2="hello";
cout <<s[0]<<"*"<< s << "*" << s2<<"*";
return 0;
}
For std::string, operator[] is only valid to index into existing data of the string. It does not cause the string to grow, it simply goes out of bounds if the string isn't already that size. To append to a string, you have several options, but to append single chars like you're doing, you'd do this:
int main(){
std::string s;
s += 'h';
s += 'i';
...
Each application of operator += causes the size of the string to grow.

Splitting a string into an array of characters using a variable for the string

I'm trying to split a string into an array of individual characters. However, I would like the string to be input by the user, for which I need to define the string using a variable.
My question is, why does this work:
#include <iostream>
using namespace std;
int main() {
char arr [] = {"Giraffe"};
cout << arr[0];
return 0;
}
But this doesn't?
#include <iostream>
using namespace std;
int main() {
string word;
word = "Giraffe";
char arr [] = {word};
cout << arr[0];
return 0;
}
Thanks
Your example doesn't work because you're trying to put a std::string into an array of char. The compiler will complain here because std::string has no type conversion to char.
Since you're just trying to print the first character of the string, just use the array accessor overload of std::string, std::string::operator[] instead:
std::string word;
word = "Giraffe";
std::cout << word[0] << std::endl;
In your second example, the type of word is a std::string and there are no default type conversions from std::string to the type char.
On the other hand, the first example works because it can be interpreted as an array of char (but actually its just c-style const char *).
If, for some reason, you would want to convert std::string into the c-style char array, you might want to try something like this...
#include <iostream>
#include <string>
#include <cstring>
int main(void)
{
std::string word;
word = "Giraffe";
char* arr = new char[word.length() + 1]; // accounting for the null-terminating character
strcpy(arr, word.data());
std::cout << arr[0] << std::endl;
delete[] arr; // deallocating our heap memory
return 0;
}

How can i store hex value in string and get the value and size of the string

I am trying to store a hex value in a string and latter retrieve it after some time, but while retrieving No value is coming size of the string is also coming 0. Sample code:
using namespace std;
int main() {
std::string s;
s.assign("\x00\x53"); // std::string s ="\x00\x53"
cout<<s.size();
}
output is coming 0
Try using \\ instead of \:
s.assign("\\x00\\x53");
Now you have:
#include <iostream>
using namespace std;
int main() {
std::string s;
s.assign("\\x00\\x53"); // std::string s ="\x00\x53"
cout << s.size() << endl;
cout << s << endl;
}
Output:
8
\x00\x53
From C++14 onwards, we have the option of using string literals, using that feature you can do this:
std::string s1 = "\x00\x53"s;
This will do what you expect and will return the correct value for size().
If you cannot use C++14 features, you need to use a string constructor that will allow you to specify the length of the string. You can do this:
std::string s1( "\x00\x53", 2);
You can see demo for both versions here.

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

string (from substr) conversion to unsigned int

I have a string which actually contains a number and a string, separated by ,, for instance "12,fooBar".
I would like to put it into separated variables, i.e. the number into unsigned int myNum and the string into std::string myStr.
I have the following snipped of code:
size_t pos1=value.find(',');
std::cout << value.substr(0, pos1) << " and "
<< (value.substr(0, pos1)).c_str() << std::endl;
This yields 12 and 1. Anything I missed here? What happend to the 2 in the second part?
Note: I isolated the problem to this snipped of code. I need c_str() to pass it to atoi to get the unsigend int. Here I don't want to print the second part.
Update: I actually get the string from levelDB Get. If I put a test string like I put here, it works.
The posted code produces the same substring: value.substr(0, pos1). Note that std::string::substr() does not modify the object, but returns a new std::string.
Example:
#include <iostream>
#include <string>
int main ()
{
std::string value ="12,fooBar";
unsigned int myNum;
std::string myStr;
const size_t pos1 = value.find(',');
if (std::string::npos != pos1)
{
myNum = atoi(value.substr(0, pos1).c_str());
myStr = value.substr(pos1 + 1);
}
std::cout << myNum << " and "
<< myStr << std::endl;
return 0;
}
Output:
12 and fooBar
EDIT:
If the unsigned int is the only piece required then the following will work:
unsigned int myNum = atoi(value.c_str());
as atoi() will stop at the first non-digit character (excluding optional leading - or +), in this case the ,.
The cleanest C++ style solution to this problem is to use a stringstream.
#include <sstream>
// ...
std::string value = "12,fooBar";
unsigned int myNum;
std::string myStr;
std::stringstream myStream(value);
myStream >> myNum;
myStream.ignore();
myStream >> myStr;
Your second substr should be value.substr(pos1+1,value.length())
One more option is using std::from_chars function from the 17th standard (< charconv > header):
int x;
from_chars(&s[i], &s.back(), x); // starting from character at index i parse
// the nearest interger till the second char pointer
There are different overloads for different types of value x (double etc.).