double to string in c++ - c++

I'm trying to convert the expression "5 + b * 18" to "5+16.89*18". My problem is inside the while loop. I managed to remove the spaces.
My code:
double number = 16.89;
size_t found;
ostringstream converted;
string str ("5 + b * 18");
str.erase(remove(str.begin(),str.end(),' '),str.end());
found = str.find_first_of (VALID_CHARS);
while (found != string::npos)
{
converted << fixed << setprecision (8) << number;
str.insert(found, converted.str());
found = str.find_first_of (VALID_CHARS,found + 1);
}
Can anyone help me?
Ty

insert() will shift the contents of the string to the right after the inserted text, but does not delete the character at the given position. You should use replace(), specifying a size of ` (to replace just a single character)

Is this homework? If not, I'd really advice against doing this kind of parsing yourself. There are dedicated libraries for this kind of things which have been extensively tested, such as muParser.

Use sprintf. It's great for converting most primitive types into strings.
int main()
{
double number = 16.89;
char buffer [50];
sprintf(buffer, "5 + %f * 18",number);
}

Related

How do I properly parse substrings so that they can be effective for my newbie calculator?

Please ELI5 if possible, since i've only been coding for a few days and this is my first program! Below is a portion of my script that is supposed to interpret a single line of input that somebody enters (like "5+5" or something).
I have other operations that I want to add later that are formatted differently, which is why I'm using string instead of a switch function or something.
Anyways.. this isn't working :( So below is my logical process and maybe somebody can point out where I messed up? :)
Thank you in advance!
if (fork.find("+" && "-" && "x" && "/"))
{
size_t pos = fork.find("+" && "-" && "x" && "/"); // Defines a position at the operator symbol
string afterfork = fork.substr(pos + 1); // Cuts a substring at the operator symbol + 1
size_t beforepos = fork.find_first_of(fork); // Defines a position at the beginning of the string
string beforefork = fork.substr(beforepos); // cuts a substring at the begninning of the string
string atfork = fork.substr(pos); // cuts a substring that only has one char (the operator +, -, x, etc)
int x = stoi(beforefork.c_str()); // converts the first substring to an integer
int y = stoi(afterfork.c_str()); // converts the third substring to an integer
string operation = atfork; // converts the middle substring that only has one char to a different name.
return input(x, operation, y); // will send this information to the input function (which will do the math for the calculator).
}
To search the string for one of a list of characters, you can use find_first_of. This function returns npos if it didn't find anything.
const size_t operatorPos = input.find_first_of("+-*/");
if (operatorPos == std::string::npos) {
std::cout << "Couldn't find an operator!\n";
return;
}
To split the string into two sub-strings, you can use substr. To get a character at a position, use operator[].
const std::string left = input.substr(0, operatorPos);
const std::string right = input.substr(operatorPos + 1);
const char operation = input[operatorPos];
To convert a string to an integer, well, there are a lot of options. I'll use std::stoi for this answer. This function throws an exception that we need to catch when it can't convert the string to an integer.
int leftInt;
try {
leftInt = std::stoi(left);
} catch (...) {
std::cout << '"' << left << "\" is not a valid integer!\n";
return;
}
int rightInt;
try {
rightInt = std::stoi(right);
} catch (...) {
std::cout << '"' << right << "\" is not a valid integer!\n";
return;
}
If exceptions are really confusing (it took me ages to get my head around exceptions!) then you can try another function. My favourite (and IMO best) is std::from_chars. Another option is to just not catch the exception.
const int leftInt = std::stoi(left);
const int rightInt = std::stoi(right);
In that case, you won't get a nice error message like "five" is not a valid integer!. You'll get something like:
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
Abort trap: 6
Try running std::stoi("five") and see for yourself!
Please, don't use using namespace std;. Just don't!

C++ getting floats out of long char array

This is probably a rookie question, but I couldn't find the answer in the search.
I got a variable:
char buffer[ 128 ];
now I've made it's value through a search script, coming from a big file to:
"Density # 15°C kg/m3 990.1 ( 991.0 Max ).BR.Viscocity #50°C cSt 355."
This is a specific line of 128 chars that I'm intrested in, more specifically the float "990.1". I need to get this out of all my files which is a bunch so getting the program to search for that specific text is not ok (I'll need to loop through a lot of files), it has to search for the first float. I've been trying with sscanf, but been stuck on it for a while now so I thought I'd ask.
Any help would be much appreciated!
If the float value you're looking for is always between kg/m3 and (space) you can use strstr to exctract the piece of string and then convert to float.
http://www.cplusplus.com/reference/cstring/strstr/
char *start;
char *end;
double val;
start = strstr( buffer, "kg/m3 " );
start += 6;
end = strstr( start, " " );
*end = 0;
val = atof( start );
*end = ' ';
Note that I look for the termination space and convert to null termination character.
So atof parses buffer starting from start and stops after the last digit.
Later I restore the space to leave the original string unchanged.
Thanks for the input everybody. So I went with the comments answer of πάντα ῥεῖ by using parsing, mainly because of the whitespace giving me issues on Paolo's suggestion. This is what has worked out for me:
float num;
string dummy;
istringstream iss( buffer );
while( !iss.eof() && dummy != "(")
{
iss >> num;
if(iss.fail()) {
iss.clear();
iss >> dummy;
continue;
}
}

Extract a specific text pattern from a string

I have a string as follows,
"0/41/9/71.94 PC:0x82cc (add)"
The desired output is the text between the brackets ( )
Ex: output = add,
for the string specified above
How is this done using sscanf?
Is there a better way to do it in C++?
With string operations exclusively:
std::string text = "0/41/9/71.94 PC:0x82cc (add)";
auto pos = text.find('(') + 1;
auto opcode = text.substr(pos, text.find(')', pos) - pos);
Demo.
With sscanf it would look something like this:
std::string opcode(5, '\0'); // Some suitable maximum size
sscanf(text.c_str(), "%*[^(](%[^)]", &opcode[0]);
Demo.
Its very easy, u should try yourself, think how to search in an array, then think if i could compare the content of an array or not, then every thing would be possible, as a programmer u have to create ideas, however if i were asked to write a program like this i would do that as follows:
int i=0, p=0;
char string="0/41/9/71.94 PC:0x82cc (add)", nstr[100];
while(string[i]!='\0')
{
while(string[i]!='(')
i++;
if (string[i]=='(')
{
i++;
goto end;
}
end:
while (string[i]!=')' || string[i]!='\0')
{
nstr[p]=string[i];
p++;
i++;
}
nstr[p]='\0';
cout<<Output = "<<nstr<<"\n";
I know this is very long, but this will give you deeper understanding of parsing or spliting a string, hope i help u, thank u...

delete a char in a string

I need to delete a specified location in a string
For example:
input: 4 Flower
output: Floer
I wrote this code but it gave an output: Flo (i.e. erased the rest of the word)
What other function, instead of erase, can I use to achieve this objective?
int main(){
int num;
int index = 1;
string s;
cin >> num >> s;
s = s.erase(num-1);
cout << index << " " << s << endl;
return 0;
}
Try:
s.erase(num-1, 1);
You are currently (effectively) calling:
s.erase(num-1, npos);
(and remove the s = bit as there is no need to reassign s).
If you are a beginner in C++ world, I would suggest you to write your own function that does it! You may use standard functions and classes anytime you would need. Some may say, why to re-invent the wheel, but its not about re-invention, but learning what invention mean, what wheel is, and how it was invented.
Writing our own code (specially for C-strings!) will give your very good programming experience, will give confidence about syntax, and most imporatantly it will enhance your logic development skills.
Your function may be like:
void RemoveCharacter(char* pString, char cCharToRemove);
Now, the question is: will it remove all occurrences of same character, or just the first one? What if there are no occurrence of given character?
Should this function return something, if it removed character, or a counter of removals? Should it take another parameter, which says "remove-all-occurrences" or not.
Happy coding!
How about this?
std::string removeChar(std::string const& input, size_t pos) {
return input.substr(0, pos-1) + input.substr(pos);
}
or this
std::string removeChar(std::string const& input, size_t pos) {
return input.erase(pos-1, 1);
}
just try
s.erase(num-1, 1), this is what you want.
The prototype of std::string::erase is
erase(size_t __pos = 0, size_t __n = npos)
If the second parameter is not supplied, the default value npos will be used and the remainder started from __pos will be removed.

Parsing a string by a delimeter in C++

Ok, so I need some info parsed and I would like to know what would be the best way to do it.
Ok so here is the string that I need to parse. The delimeter is the "^"
John Doe^Male^20
I need to parse the string into name, gender, and age variables. What would be the best way to do it in C++? I was thinking about looping and set the condition to while(!string.empty()
and then assign all characters up until the '^' to a string, and then erase what I have already assigned. Is there a better way of doing this?
You can use getline in C++ stream.
istream& getline(istream& is,string& str,char delimiter=’\n’)
change delimiter to '^'
You have a few options. One good option you have, if you can use boost, is the split algorithm they provide in their string library. You can check out this so question to see the boost answer in action: How to split a string in c
If you cannot use boost, you can use string::find to get the index of a character:
string str = "John Doe^Male^20";
int last = 0;
int cPos = -1;
while ((cPos = str.find('^', cPos + 1)) != string::npos)
{
string sub = str.substr(last, cPos - last);
// Do something with the string
last = cPos + 1;
}
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
Do something like this in an array.
You have a number of choices but I would use strtok(), myself. It would make short work of this.