Adding char which is a math operator to random string [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to add "+", "-", "*" etc. to a string but it doesn't work.
Lets say I have string "12 3 +" Then I use string tmp to get values between spaces like "12" "3" "+". my cout prints "12" and "3", but "+" is missing
int ONP() {
string wyrazenie;
getline(cin, wyrazenie);
string tmp;
for (int i = 0; i < wyrazenie.length(); ++i) {
if (!isspace(wyrazenie[i])) {
tmp += wyrazenie[i];
} else {
cout << tmp << endl;
SOME CODE.....
tmp.clear();
}
}
}

Issue is that + is your last character, so you won't go in else block for it.
std::cout temp after the loop would show your missing character:
Demo

Your loop will never display the last token of the string unless the string ends in a space. When you have "12 3 +" you read in the 12 see a space, print the 12 and clear the string. You do the same thing for 3. Then you get + but since that is the last character in the string you never run the else part of the if statement to print it out. You can fix this a few ways. You can check if temp is not empty after the loop and if it is not then handle that. You can rework your logic in the loop to handle when you are on the last character and it is not a space. You could add a space to the end of the input so it will end with a space and the loop works as is.

From the code you provided, I see an issue that would cause the last character to not be printed. This is because you are only printing tmp when the next character is a space. So "12 3 +" would print "12", "3". Then tmp contains the value "+" since its never printed nor cleared, but is never printed. If your input string is "12 3 + " (notice the space) the '+' char would be printed too.
This can be solved with printing and clearing tmp after the loop is done if tmp still contains any data.

Related

Problem storing characters as an string inside a while loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm having problems with this simple example.
The program inquires as to how many letters are required to form a complete word. Then it will ask for each letter individually, which is fine, but I can't make the code save the value from the current character and the next one from the next iteration until the number of letters finishes the word and print it to confirm the word.
E.g. Let's say house, which has 5 letters.
int numbersOfCharacters=5;
int counter=0;
char character;
string phrase;
while (counter < numbersOfCharacters)
{
cout << "Introduce character's number" << counter << ": ";
cin >> character;
counter = counter + 1;
phrase=character+character; //I'm not sure if I need an array here.
}
cout << "Concatenated characters: " << phrase << endl;
The output is:
Introduce the character number 1: h
Introduce the character number 2: o
Introduce the character number 3: u
Introduce the character number 4: s
Introduce the character number 5: e
Concatenated characters: ?
And the expected output should be:
Concatenated characters: house
Update
Using John's comments I was able to resolve the issue. It's not a lack of debugging information but instead know the proper operator for this solution. Thanks also to Remy Lebeau for the detailed info.
The expression phrase=character+character; doesn't do what you think it does. You are taking the user's input, adding its numeric value to itself, and then assigning (not appending) that numeric result as a char to the string.
So, for example, on the 1st iteration, the letter h has an ASCII value of 104, which you double to 208, which is outside the ASCII range. On the next iteration, the letter o is ASCII 111 which you double to 222, which is also outside of ASCII. And so on. That is why the final string is not house like you are expecting.
Perhaps you meant to use phrase=phrase+character; instead? But, that won't work either, because you can't concatenate a char value directly to a string object using operator+.
What you can do is use string::operator+= instead:
phrase += character;
Or the string::push_back() method:
phrase.push_back(character);

Check an Array String character value without extra variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
suppose I've this code:
string str[] = {"devil", "chandra"};
// check if str[0] has properly devil, character by character or not without extra variable
Now I want to check str[ 0 ]'s all character which is 'd','e','v','i','l' one by one without extra variable.
with extra variable code will be :
string n1 = "devil";
for(int i=0; i<1; i++){
string s1 = str[i]
for(int j=0; j<s1.size(); j++){
if(s1[i] == n[i]){
cout << s1[i] << " ";
}
}
Basically, I want O(n) loop where I can access all indexes string and among them all characters.
Like s[ i ] is "devil" and s[[i]] = 'd' something like this, Know it's not valid, but is there any way to do that??
Even I don't know is it a valid question or not!
I'm not sure why you would need an extra variable. If you need a conditional that checks that the first value in the array of strings is "devil", it shouldn't be anymore complicated than:
if (str[0] == "devil")
{
* Do things *
}
C++ can check a standard string all at once. You don't need to check each individual character if that's what you're thinking.
Keep in mind, this isn't going to account for situations where the string is not exactly the same. For instance, if str[0] has "Devil" instead of "devil", then the conditional will evaluate to false.

Can someone explain this C++ code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am a new here. I do not understand the if statement: i==0, It eliminates repetition. How it works? Thanks.
vector<string>words;
for (string temp; cin >> temp;)
words.push_back(temp);
cout << "Number of words:" << words.size() << '\n';
sort(words);
for (int i = 0; i < words.size(); ++i)
if (i == 0 || words[i - 1] != words[i])
cout << words[i] << '\n';
If i equals 0, then you can't look words[i-1] because you can't do words[-1]
Furthermore, when you use || operator, if the first expression is true, the second expression is not checked
With i == 0 || words[i - 1] != words[i] you can print your first words because i equals 0 and the expression words[i - 1] != words[i] isn't checked and doesn't crash your program !
then with i different from 0, the first expresion isn't true and the second is checked.
For the unrepetition part :
Your array is sorted, so same words are one after another.
Then you have to check if the previous word isn't the same, you can print the word
How words[i - 1] != words[i] works :
for std::string, operators == and != look for the length of each string, and each character in the string
Comparison operator for std::string
Moreover, words[i-1] look for the previous words, and words[i] for the current one, to compare them.
So here, the expression is true if the two consecutives words aren't the same, in length and letters.
if you have words dog cat cat cat_ in your array, dog is printed first (because of the i == 0 part), the second word cat is printed, then the epression is false because the words are identical ("cat" == "cat"), and finaly, cat_is printed because different from cat
This program is first sorting all the words which are a vector of strings, and prints only unique word.
i==0 means the first word, Since you can't compare the first word with any previous so it will always be unique(from its previous words which doesn't exist)
word[i-1]!=word[i] check if the current word is different from previous the print that word.
|| is a Logical Or operator.
looks like your program prints the first word, and every other word that isn't repeated in a sorted list of words. If you're trying to look for unique words, try using std::unique.

decoding a character array [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 7 years ago.
Improve this question
Given a character array in a URL format like
char *s="www.google.com\tsp finite.aspx"
While decoding it space should be replaced by %20 and thus the string becomes:
char *s="www.google.com\tsp%20finite.aspx"
We are not allowed to use a new character array but allowed to use some character variables for temporary use. Should not use any containers also. The array contains enough space to contain the decoded data so no need to worry about the more space to be taken.
I followed the Brute-Force mechanism where all the characters from the point of finding a space to the end of the array are to be swapped. But this is not the most efficient way to solve the problem.
Can any body tell me which is the best way (algorithm) to decrease the no. of swappings in order to acquire the solution.
I am assuming the string has been allocated using malloc
First calculate the number of spaces and the length of the string
Then the new length = old length + number of spaces * 2. Use realloc to expand the string.
The work backwards from the end and copy to the new length. When encountering space copy in %20 instead.
The main problem could be that swapping space with %20 will require moving the whole string 2 characters more .
Here's an idea :
Parse the whole string once, and count the number of spaces in the string
The new length of the array would be strlen(original) + 2*(nOfSpaces) (let's call it from now on NewLen)
Parse the whole string once again but starting backwards.
You will copy the previous string contents inside itself but at an offset until you hit a space
you will have a pointer starting at strlen(original) and one starting at NewLen
parse from strlen(original) backwards until you find a space (the substrLen will be subLen)
memcpy from [strlen(original)-curParsingindex] to [NewLen - curParsingIndex-2*(enteredSpaces)] sublen amount
Instead of copying the space, put %20 instead
This way you will avoid moving the string forward each time you hit a space.
Regarding step 4 , you might think about using a temporary variable for the sublen, since you might end up writing in the same memory zone by mistake (take an example where all the spaces are at the beginning).
This is a classic interview coding question; a good solution for this starts with a good interface for your solution. Something that works is:
char* replaceChar(char* in, char c)
char *in - string you want to decode
c - the char you want to replace with it's hexa value ASCII code ( HEX val ascii for ' ' is 0x20)
Pseudocode:
allocate a buffer the same size as the input buffer
get the index of the first occurrence of the char you want to replace (strcspn can help with that)
copy the content of the of the input up to the found index to the new buffer.
reallocate the new buffer size to newSize=oldSize+2
add % to the new string
repeat until you reach the end of the string.
return a pointer to the new string
You can also do it in place on the original string but that solution is a bit more complicated because you have to shift everything.
You can do it in two passes. The key idea is to first count the number of spaces and then move each character directly to its final position. In your approach you shift the remainder of the string at each occurrence of a space.
#include <stdio.h>
int main ()
{
char str[1000] = "www.example.com/hello world !";
int length;
int spaces;
int i;
char *ptr;
printf ("\"%s\"\n", str);
// pass 1:
// calculate length and count spaces
length = 0;
spaces = 0;
for (ptr = str; *ptr; ptr++) {
if (*ptr == ' ') {
spaces++;
}
length++;
}
// pass 2:
// transform string
// preserve terminating null character
ptr = str + length + 2 * spaces;
for (i = length; i >= 0; i--) {
char c = str[i];
if (c == ' ') {
*ptr-- = '0';
*ptr-- = '2';
*ptr-- = '%';
}
else {
*ptr-- = c;
}
}
printf ("\"%s\"\n", str);
return 0;
}

How to get a user to input 10 letters, then stores these in a char array [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 9 years ago.
Improve this question
I've tried this, but I having no luck, I'm am looking to get user input 5 letters and then print them out.
string input = "";
const int max = 5;
char string[max] = { };
cout << "Please enter 5 letters: " << endl;
cin.getline(string, max, '\n');
cout << "Your letters :" << string[max];
I think I figured out what's not working:
First, you are printing out string[max] at the end. Since string is a char[] of size max, it actually has no data at index max--its indices are 0 to max-1. You are actually printing out a random character from whatever happens to be in memory immediately after the characters of your string variable.
So instead of << string[max] in the last line, it should be << string.
Second, after making that change, it will still seem to print only 4 characters, instead of the 5 that were entered. This is because strings in the form of char[]s have a null terminator. So since you are telling cin.getline to only fill up 5 characters in string, it fills the first 4 with actual characters from input, and then the last character is '\0'.
So if the input is "hello", then string will contain the following values: { 'h', 'e', 'l', 'l', '\0' }. And then when you print it, there are, of course, really only 4 characters in the array.
And two notes: string input is not used anywhere in your program, so it should be taken out of the question. And also, you really should call your char string[max] variable something else, to reduce confusion.
I hope this helps!