Strange behaviour while adding string to another string in C++ [duplicate] - c++

This question already has answers here:
How can I repeat a string a variable number of times in C++?
(10 answers)
Closed 2 years ago.
one is 2, and ans is "000000".
string ans = "000000";
ans += string("1", one);
cout<<ans<<endl;
The output is:
0000001�
But I want the output:
00000011
What am I doing wrong?

string("1", one) does not do what you think it does. It does not duplicate the "1" string one number of times. It instead copies the 1st one number of chars from "1", which in this case is the '1' character and the '\0' null-terminator that follows it, which is where the � is coming from in the output. That is not what you want.
Use string(one, '1') instead. That will duplicate the '1' character one number of times, like you want, eg:
ans = "000000";
ans += string(one, '1');
cout << ans << endl;

Just use c++ strings and use + operator to catenate strings.

Related

Can someone tell me the output and provide explanation of the following c++ code? [duplicate]

This question already has answers here:
C++ character concatenation with std::string behavior. Please explain this
(3 answers)
Closed 1 year ago.
cout<<"#" + 'a'<<endl;
string s = "#";
s += 'a';
cout<<s<<endl;
I am not able to figure out how the typecasting is working in the case "#" + 'a'
In cpp string works like an array of characters, so when you assign s = '#' it compiles like this:
s[0] = '#'
and in the second line it actually compiles like this:
s[1] = 'a'
finally, s is:
#a

Why when a character array is compared to another character array, output is wrong but when character array is compared to a string output is correct? [duplicate]

This question already has an answer here:
C++ string and string literal comparison
(1 answer)
Closed 1 year ago.
Question - The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
Input -
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output -
If the word t is a word s, written reversely, print YES, otherwise print NO.
When I write this code, the output is wrong -
int main(){
char s[100000],a[100000];
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
But when I write this code, the output is correct -
int main(){
char s[100000];
string a;
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
Why is it like this, is there a rule that a character array cannot be compared to another character array and if so, how can it be compared to a string?
Remember that arrays naturally decay to pointers to their first elements, and it's such pointers that you are comparing.
In short, what you're really doing is:
if(&s[0] == &a[0])
And those two pointers will never be equal.
To compare the contents of character arrays, you need to use strcmp() or similar function instead, eg:
if(strcmp(s, a) == 0)
Since you're programming in C++, please use std::string for all your strings. There are overloads for the == operator that do the right thing if you have std::string values.

Different answers with single and double quotes while displaying in C++ [duplicate]

This question already has answers here:
What do single quotes do in C++ when used on multiple characters?
(5 answers)
Closed 6 years ago.
I have displayed a statement in C++ program with single quote and answer which i got was the random numbers where as when i used the double quotes in C++ it displayed me the statement.
cout << 'Hello world'; //gave me the random numbers
cout << "Hello world"; //displayed me the statement i.e Hello world
Why This happened pls do let me know and what those random numbers were at the time of execution ?
Single quotes are used for characters:
char c = 'A';
In case you want to print a string which is more than one character, you use double quotes:
cout << "Hello World";
You are trying to print an array of characters, which require double quotes.
char str[3] = "abc"; //an array of characters, use double quotes
str[0] = 'x'; //set a character in this array, use single quote

No output from cout string when the values are entered using indexes [duplicate]

This question already has answers here:
Change string by index
(3 answers)
Closed 7 years ago.
string l;
cin>>l[0];
cout<<l;
input:a
output:
According to me the code must print the value of l[0] but why is there no output?
You need to do
cin>>l;
In your current state of code, when you try to access l[0] you are trying to access a memory location which may or may not be there. cin >> l[0] doesn't changes the size of the string which remains 0.
So when you try to do cout << l you are effectively printing an empty string.
Another alternative is
string s;
s.resize(1);
You have an empty string. There are no characters in it, including 0th character, you trying to read into. You need to actually add characters in string:
std::string l;
l.push_back('\0'); //Or any other character
std::cin >> l[0];

Separating number input into units [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I need to separate users input into units and store them in an array.
e.g if user enters 6547. Array will store {6,5,4,7} Using C++ on Linux
I would appreciate if you can help me with pseudocode or explain an algorithm.
I'm a beginner so please restrain from advising advanced function (and explain its use if you do) as we have studied basics so far
N.B| If such question has already been answered and I skipped it in search, please do point me to it.
The math for isolating right most digit:
digit = digit % 10;
The math for shifting a number right by one digit:
new_number = old_number / 10;
Every letter and number can be represented as a text character. For example, '5' is a character representing the single decimal digit 5.
The math for converting a textual digit (character) to numeric:
digit = char_digit - '0';
Example:
digit = '9' - '0';
The math for converting a numeric digit to a textual digit (character):
char_digit = digit + '0';
Example:
char_digit = 5 + '0';
Your problem basically breaks into few parts, which you need to figure out:
how to read one character from input
how to convert one character to the digit it represents
how to store it in the array
Please, try to explain if you have problem with some particular point from the list above or there is a problem somewhere else.
Suppose Variable input_string holds the number entered by the user & you want to store it in an array named 'a'...Here's a C snippet.. you can easily convert it into C++ code..
I would recommend taking the input as string rather than int so that you can directly insert the digits extracted from the end...(else you can start storing the integer from beginning and then reverse the array)
scanf("%s",&input_string)
size = strlen(input_string)-1
input = atoi(input_string)
while (input/10>0)
{
i=input%10;
input=input/10;
a[size]=i;
size--;
}
Hope that helps!
Here's a C++11 solution:
std::string input;
std::cin >> input;
int num = std::stoi(input);
std::vector<int> v_int;
for (unsigned int i = 0; i < input.size(); i++)
{
v_int.push_back(num % 10);
num /= 10;
}
// To get the numbers in the original order
std::sort(v_int.rbegin(), v_int.rend());
for (unsigned int i = 0; i < v_int.size(); i++) {
std::cout << v_int[i] << std::endl;
}
If you want it in a c-style array, do this:
int* dynamic_array = new int[v_int.size()];
std::copy(v_int.begin(), v_int.end(), dynamic_array);
delete dynamic_array;