Char seperated by a decimal into a double c++ [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 passing a string variable (std::string) and iterating through the string character by character. Whenever I run into a decimal, I want to combine the previous position on the string (i.e 2) and the next position in the string (i.e 5) into a double. So how would I go about making the char 2, char . , char 5 into one whole value (2.5)?
std::double x;
std::string varibleName = "4 5 7 2.5";
for (int i = 0; i < variableName.length(); i++) // iterates through variableName
{
if (variableName[i] == '.'){ // if the current position of the iteration is a decimal, I want to grab the char before the decimal and the char after the decimal so I can combine all three positions of the string making it 2.5 and not 25.
}
}

Well, you are wildly overthinking it. The C++ library provides std::stof, std::stod, std::stold that does exactly what you want. Convert a string like "2.5" to a float, double or long double, e.g.
#include <iostream>
int main (void) {
std::string s = "2.5";
double d = std::stod(s);
std::cout << d << "\n";
}
Example Use/Output
$ ./bin/stodex
2.5
Look things over and let me know if you have further overthinking questions.

Note that giving an example, code snips, and error logs make troubleshooting a lot easier :)
It sound like you have some input like "2.1" and need to convert it to a double like 2.1?
If that is the case you can use the <cstdlib> atof function.
Example:
/* atof example: sine calculator */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atof */
#include <math.h> /* sin */
int main ()
{
double n;
char buffer[256];
printf ("Enter degrees: ");
fgets (buffer,256,stdin);
n = atof (buffer);
printf ("You entered %s which is a double like %f\n" , buffer, n);
return 0;
}

Related

weird when use atof in Visual Studio [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
When I used VS 2015 to debug the following code,
int main()
{
char thev[8] = "0.12345";
float fv = atof(thev);
printf("%f\n", fv);
return 0;
}
the value of fv in watch window is 0.12345004,
and printf is 0.123450, how to let fv=0.12345 in the run time?
There is similar post, here, but no answer there, can somebody help me?
And I pasted that code to my VS 2015,
int main()
{
const char *val = "73.31";
std::stringstream ss;
ss << val;
double doubleVal = 0.0f;
ss >> doubleVal;
}
the value doubleVal in watch window is 73.310000000000002
Replace the following code:
printf("%f\n", fv);
with:
printf("%.5f\n", fv);
Explaination:
we use a width (%.5f) to say that we want 5 digits (positions) reserved for the output.
The result is that 5 “space characters” are placed before printing the character. And the next character will be not printed.
Reference: https://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
There is no exact representation in IEEE single precision for 0.12345. The closest two values on either side of it are 0.123450003564357757568359375 and 0.12344999611377716064453125. atof is picking the former, I think because it is closer to 0.12345 than the latter.

Handling strings inside Files [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 6 years ago.
Improve this question
I'm trying to save data from a file into an array but I've had no luck for now. It's easy to save data after it was read from the file in case it's just numbers, but for example if I'm trying to save strings, the program keeps crashing over and over again. I'm using fscanf(); function since the whole .txt file is written in the same format: "First Name, Last Name". Now then, I've tried using the for loop in this way:
char *firstName = (char*)malloc(sizeof(char)*10240);
char *lastName = (char*)malloc(sizeof(char)*10240);
for(int i = 0; i<10; i++){
fscanf(fp, "%s %s", firstName[i],lastName[i]);
}
And that's where it crashes.
Pure C code:
You have to allocate the array of arrays first, then allocate each string one by one
It's best to scan the strings into temp strings with a big size, and duplicate the strings later.
int i,nb_names = 10;
char **firstName = malloc(sizeof *firstName * nb_names);
char **lastName = malloc(sizeof *lastName *nb_names);
char tempn[1000],templ[1000];
for(i = 0; i<nb_names; i++){
fscanf(fp,"%s %s", tempn,templ);
firstName[i] = strdup(tempn);
lastName[i] = strdup(templ);
}
Note that I have changed for (int i to for (i because it is not C compliant but rather C++ compliant (or C99, not sure).
For C++, drop the mallocs and use std::vector and std:string instead.
I'd recommend to use C++ if you can. I answered a lot of C/C++ questions on people trying (and failing) to allocate 2D arrays properly (including me 5 minutes ago damn :)). C++ using C++ library code is much clearer.
Full C++ example, reading from standard input
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int nb_names = 10;
vector<string > firstName(nb_names);
vector<string > lastName(nb_names);
for(int i = 0; i<nb_names; i++){
cin >> firstName[i];
cin >> lastName[i];
}
return 0;
}
The error in your code is : firstName[i] is a character not a string but you use it like a string by using %s instead of %c.
you should use a char ** instead of char *.
char **firstName = (char**)malloc(10*sizeof(char)*10240);
I think also that 10240 is too much for firstName. Use 255 or less.

C++ Calculator With Unlimited Inputs [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 4 years ago.
Improve this question
Hi I am a beginner to the c++ language and I would like to know if there is any way of writing a program with unlimited inputs. For example: I want to write a calculator program just to add numbers. That's easy enough but is there a way so that the user can add as many numbers as he wants without being asked how many numbers he wants. Such that if he wants to add three numbers he can just type "1+1+1" or if he wants to add four numbers he adds "+1" to the end of the previous line.Like this the user is not stuck to a fixed number of inputs or so he doesn't need to be asked how many inputs he wants. What functions in c++ do I need to know in order to do this
You can use a while loop to read from standard input. (std::cin) Some basic code to read from a while loop, and add the input to a sum is as follows:
#include <iostream>
#include <string>
#include <cstdlib>
int main(){
std::string line = "";
double sum = 0.0;
while(line != "end"){
std::cout<<"The current sum is: "<<sum<<std::endl;
std::cout<<"Enter the number you would like to add or \"end\" to exit: ";
std::cin>>line;
sum += atof(line.c_str());
}
std::cout<<"The final sum is: "<<sum<<std::endl;
}
This will read numbers until it receives the input "end".
For parsing and evaluating expressions that include infix operators, few things are simpler than the Shunting Yard Algorithm.
Implementing this in C++ is scarcely different than any other language with a container library (or built-in support) that provides stacks and queues. Here, you'll want to use std::stack and std::queue. The input to your program could be a single line (containing an expression typed by the user) read from std::cin (standard input, or the console) into an std::string.
This will not only permit expressions of any reasonable length, but also correctly handle arbitrary nesting of parenthesized sub-expressions, evaluation of special functions, and custom operators.
Yes. It is possible. You can use vector of ints. Get user's input and calculate sum of elements from vector. Put this in loop and that is what you wanted.
try this:
#include <iostream>
int main (int argc, char *argv[])
{
for (int i = 0; i < argc; i++)
std::cout << "argument " << i << " is " << argv[i] << std::endl;
return 0;
}

String to hex char array [duplicate]

This question already has answers here:
How can I assign hex string to a char[] variable?
(7 answers)
Closed 8 years ago.
I get a string which is given as an argument to a function like e.g. 00112233445566778899aabbccddeeff and I need to make an unsigned char array of it which looks like this:
unsigned char array[16]= {0x00 ,0x11 ,0x22 ,0x33 ,0x44 ,0x55 ,0x66 ,0x77 ,0x88 ,0x99 ,0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff};
I have no idea how to do it, tried some things with strcpy and thought about hex but this works only with << or >> as I know so I don't think I know how to apply it here. Anyone could help please?
It seems you need to convert each digit received to a nibble and to combine two nibbles into a byte. The conversion from digit to nibble can be done using a look-up or using conditional logic for digits and letters. The combination is a bitwise shift and a bitwise or.
I could write the code but I've somewhat outgrown assignments, not to mention that my version is unlikely to be a viable solution anyway.
You could do this with a combination of istringstream and std::hex.
example
#include <iostream>
#include <sstream>
int main() {
std::string myStr = "1122AA010A";
std::stringstream ss;
int n;
for(int i = 0; i<myStr.length(); ) {
std::istringstream(myStr.substr(i,2))>>std::hex>>n;
ss<<(char)n;
i += 2;
}
std::string result = ss.str();
std::cout<<"\n"<<result<<"\n";
return 0;
}

How can I replace percent sign (%) with two %'s? [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 want to try replace a percentage sign in a char array with two %% signs. Because a % sign causes problems, if I write as output char array. Therefore percentage sign must be replaced with two %% signs without using string.
// This array causes dump because of '%'
char input[] = "This is a Text with % Charakter";
//Therefore Percent Sign(%) must be replaced with two %%.
You can use an std::string to handle the necessary memory re-allocations for you, plus a boost algorithm to make everything easier:
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
int main()
{
std::string input("This is a Text with % Charakter and another % Charakter");
boost::replace_all(input, "%", "%%");
std::cout << input << std::endl;
}
Output:
This is a Text with %% Charakter and another %% Charakter
If you can't use boost, you can write your own version of replace_all using std::string::find and std::string::replace:
template <typename C>
void replace_all(std::basic_string<C>& in,
const C* old_cstring,
const C* new_cstring)
{
std::basic_string<C> old_string(old_cstring);
std::basic_string<C> new_string(new_cstring);
typename std::basic_string<C>::size_type pos = 0;
while((pos = in.find(old_string, pos)) != std::basic_string<C>::npos)
{
in.replace(pos, old_string.size(), new_string);
pos += new_string.size();
}
}