How to change a char to a string? [closed] - c++

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 have this function:
void map()
{
map<char, string> change;
string usrstr = "A APPLE AND BANANA";
change['A'] = "00011";
change['B'] = "11001";
change['C'] = "01110";
change[' '] = "$$";
}
How would I go about changing all occurrences of 'A' in my string to "00011" and the same for B, C and space. All help is much appreciated
P.S The string wont always be the same

Not sure to understand: how about:
std::string str = "A APPLE AND BANANA";
std::replace(str.begin(), str.end(), "A", "00011" );
std::replace(str.begin(), str.end(), "B", "11001" );
...

You can and should probably use string::replace.
Even with your most recent comment.
But this might have been what you were trying to do:
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>
using namespace std;
int main()
{
char temp;
map<char, char*> change;
string lol = "A APPLE AND BANANA";
change['A'] = "00011";
change['B'] = "11001";
change['C'] = "01110";
change[' '] = "$$";
for (int i = 0; i < lol.length(); i++)
{
temp = lol[i];
if (change[temp])
cout << change[temp];
else
cout << lol[i];
}
cout << endl;
cin.get();
return 0;
}

Related

strcmp can't convert char* to const char* in a prefix evaluation code (c++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I'm writing a code to evaluate a prefix expression. The values of the expression are separated by spaces. So if the input is "+ * 87 89 666", I should get 8409 as the answer. The concept of my code is to store the values to an array and then evaluate them value by value. Right now I'm stuck at the switch part because the compiler says invalid conversion from char to const char*
#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
char n[99999][6]={};
int evaluatePrefix(int l)
{
stack<int> Stack;
for (int j = l; j >= 0; j--) {
string x=n[j];
if (n[j][0]!='+' || n[j][0]!='-' || n[j][0]!='*' || n[j][0]!='/'){
stringstream ss;
int a;
ss<<x;
ss>>a;
Stack.push(a);
}
else {
int o1 = Stack.top();
Stack.pop();
int o2 = Stack.top();
Stack.pop();
if (strcmp(n[j], '+')==0){
Stack.push(o1 + o2);
}
else if (strcmp(x, '-')==0){
Stack.push(o1 - o2);
}
else if (strcmp(x, '*')==0){
Stack.push(o1 * o2);
}
else if (strcmp(x, '/')==0){
Stack.push(o1 / o2);
}
}
}
return Stack.top();
}
int main()
{
char e[99999], w[99999];
int i=0;
scanf("%[^\n]%*c",e);
char *token = strtok(e, " ");
while (token != NULL)
{
strcpy(n[i], token);
token = strtok(NULL, " ");
}
return 0;
}
You wrote:
if (strcmp(n[j], '+')==0)
n[j] decays into a char*, but '+' is a single char, not a char*. strcmp needs two char pointers.
https://en.cppreference.com/w/c/string/byte/strcmp
So, you should use:
if (strcmp(n[j], "+")==0)

Get the last token out of wchar_t* [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 1 year ago.
Improve this question
I have a wchar_t* in my C code, that contains URL in the following format:
https://example.com/test/...../abcde12345
I want to split it by the slashes, and get only the last token (in that example, I want to get a new wchar_t* that contains "abcde12345").
How can I do it?
Thank you?
In C, you can use wcsrchr to find the last occurence of /:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int main(void){
wchar_t *some_string = L"abc/def/ghi";
wchar_t *last_token = NULL;
wchar_t *temp = wcsrchr(some_string, L'/');
if(temp){
temp++;
last_token = malloc((wcslen(temp) + 1) * sizeof(wchar_t));
wcscpy(last_token, temp);
}
if(last_token){
wprintf(L"Last token: %s", last_token);
}else{
wprintf(L"No / found");
}
}
Just use std::wstring.
int main()
{
std::wstring input = L"https://example.com/test/...../abcde12345";
auto separatorPos = input.rfind(L'/');
if (separatorPos == std::wstring::npos)
{
std::cout << "separator not found\n";
}
else
{
auto suffix = input.substr(separatorPos + 1);
std::wcout << suffix << L'\n';
}
return 0;
}

Why is this code to reverse a word not working? [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 1 year ago.
Improve this question
I'm new to C++. I've written a small code to reverse a word. But it is not showing any output. Please explain.
void * reverse(char * arr)
{
int endindex;
endindex=length(arr)-1;
char * str;
int i=0;
while(endindex>0)
{
str[i]=arr[endindex];
i++;
endindex--;
}
str[i++]=arr[endindex];
str[i]='\0';
cout<< str;
}
Using C++ and the standard library, reversing a string is as simple as:
#include <algorithm> // std::reverse
#include <iostream>
#include <string> // string class
int main() {
std::string str{"Reverse me!"};
std::reverse(str.begin(), str.end());
std::cout << str << '\n';
}
Output:
!em esreveR
As was pointed out, the code above doesn't really help you with your code. My intent was to illustrate that no, you're not really learning C++, but C, and not good C at that. The library <cstring> provides a function strlen(), for example, which calculates a C-string length for you. I take umbrage with beginner assignments that ask you to replicate library functions.
Since I feel that the comments under your question help you sufficiently with your code, here's my take a more C-like approach:
#include <cstring>
#include <iostream>
/*
* Function to reverse the characters of a C-string
*
* Return: None
*
* Parameters:
* str: The string to be reversed; is reversed in-place
*
* NOTES:
* - Normally, when passing a C-array, you should always pass
* the size along as well. Since this function caters
* exclusively to C-strings, I'll make an exception
*/
void reverse_c_string(char* str) {
// My preference for the foor loop is minor, but
// better contains the variables concerned with the loop
for (int i = 0, endIdx = std::strlen(str) - 1; endIdx > i; ++i, --endIdx) {
int tmp = str[i];
str[i] = str[endIdx];
str[endIdx] = tmp;
}
}
int main() {
char phrase[] = "Reverse me!";
std::cout << phrase << '\n';
reverse_c_string(phrase);
std::cout << phrase << '\n';
}
Output:
Reverse me!
!em esreveR

C++ char array to int [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 6 years ago.
Improve this question
I am new to C++ and I am creating a small program. Part of it I have created a way of converting a char array to set of int's. But i was just wondering if there is a better way (more efficient and/or uses better C++ standards). Like for example using atoi on spliced part of the array for each number for etc.
So I start of reading a set of numbers e.g. "11 2 123 44" from a file into a char * array and now want to convert them into there respective values currently doing it as follows:
//char * char_cipher; //{'1', '1', ' ', '2', ... , '4'}
//int length; //length of char_cipher
string s = "";
vector<int> cipher_int;
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
Any help would be much appreciated thanks :)
Your code is pretty close. The problem is that you never push the last number in char_cipher onto cipher_int, because there's no space after it. You need to do an extra check after the loop is done.
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
if (s != "") {
cipher_int.push(back(stoi(s));
}
Let the STL do the parsing for you. You can use a std::istringstream for that, eg:
#include <string>
#include <sstream>
#include <vector>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
int num;
while (iss >> num) {
cipher_int.push_back(num);
}
Alternatively:
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
std::copy(
std::istream_iterator<int>(iss),
std::istream_iterator<int>(),
std::back_inserter(cipher_int)
);

code conversion: Matlab to C++ [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 have a very useful code bit in matlab.
I am using this code bit to save files in different parts of my code, without overwrite existing ones.
Can someone please guide me how to translate this code to C/C++ ?
i=0;
name= ['test_', int2str(i)];
while exist(name)
i=i+1;
name= ['test_', int2str(i)];
end
save(name)
In C++ on Windows I'd use something like :
#include <iostream>
#include<fstream>
#include<string>
#include<sstream>
template <typename T>
std::string num2str ( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
inline bool if_exists (const std::string& name) {
std::ifstream f(name.c_str());
if (f.good()) {
f.close();
return true;
} else {
f.close();
return false;
}
}
std::string get_next_file( void )
{
int i=1;
while (if_exists("test_" + num2str(i) ) )
i++;
return std::string("test_") + num2str(i);
}