Code to separate the whole part and decimal part - c++

Screenshot of the outputs i got for the codeHow to code to separate the whole part and decimal part
I wrote this code but it gives different values at times. I don't know why?
#include <iostream>
using namespace std;
int main()
{
float f, a, b;
int x, y, c;
cout << "enter the float value" << endl; cin >> f;
x = (int)f; cout << "before " << x;
a = b = f;
c = 1;
while (b != int(a))
{
b = b * 10;
a = a * 10;
c = c * 10;
}
y = (f * c) - (x * c);
cout << "after " << y;
}
enter the float value
22.47
before 22 after 46
user#user:~/cpp$ ./a.out
enter the float value
2234.127
before 2234 after 126
user#user:~/cpp$ ./a.out
enter the float value
22.335
before 22 after 334
user#user:~/cpp$ ./a.out
enter the float value
222.88
before 222 after 88
these are a few values i tried.

How to code to separate the whole part and decimal part?
I assume that you want to only represent the floating value into non-decimals part and decimals part. In that case, take the user input as an std::string, and do as follows. I hope the comments will get you through the code:
(See live example)
#include <iostream>
#include <string>
#include <cstddef> // std::size_t
int main()
{
std::cout << "enter the float value\n";
std::string strInput; std::cin >> strInput; // take the user input as std::string
std::size_t pos{ 0 };
// find the position of charector decimal point('.') using std::string::find
pos = strInput.find(".", pos);
// if the decimal point is found in the user input: x = substring starting from 0 to pos of user input.
const std::string x = pos != std::string::npos ? strInput.substr(0, pos) : strInput;
// if the decimal point is found in the user input: y = substring starting from pos + 1 to end of user input.
const std::string y = pos != std::string::npos ? strInput.substr(pos + 1) : std::string{ "" };
std::cout << "before " << x << " after " << y << '\n';
return 0;
}
sample input:
enter the float value
0123.04560
Output:
before 0123 after 04560
PS: However, like in the example given above, having zero before the separated decimal parts(both 0123 and 04560) might be unwanted. In that case, use any of the standard functions to convert them back to integers or remove zeros from from the beginning using erase-remove idiom.

Related

The input is a three-digit number. Print the arithmetic mean of its digits

I have a homework assignment. The input is a three-digit number. Print the arithmetic mean of its digits. I am new to C++ and cannot write the code so that it takes 1 number as input to a string. I succeed, only in a column.
#include <iostream>
int main()
{
int a,b,c;
std::cin >> a >> b >> c;
std::cout << (a+b+c)/3. << std::endl;
return 0;
}
If you write it in Python it looks like this. But I don't know how to write the same thing in C ++ :(
number = int(input())
digital3 = number % 10
digital2 = (number//10)%10
digital1 = number//100
summ = (digital1+digital2+digital3)/3
print(summ)
The most direct translation from Python differs mostly in punctuation and the addition of types:
#include <iostream>
int main()
{
int number;
std::cin >> number;
int digital3 = number % 10;
int digital2 = (number/10)%10;
int digital1 = number/100;
int summ = (digital1+digital2+digital3)/3;
std::cout << summ << std::endl;
}
In your code, you use three different numbers and take the mean of their sum (not the sum of three-digits number). The right way is:
#include <iostream>
int main()
{
int a;
std::cin >> a;
std::cout << ((a/100) + ((a/10)%10) + (a%10))/3.<< std::endl;
return 0;
}
EDIT: This answer is incorrect. I thought the goal was to average three numbers. Not three DIGITS. Bad reading on my part
*Old answer *
I'm not sure I'm interpreting the question correctly. I ran your code
and confirmed it does what I expected it to...
Are you receiving three digit chars (0-9) and finding the average of
them? If so, I'd trying using a
for loop using getChar()
Here is a range of functions that may be of use to you.
Regex strip
Convert string to int: int myInt = stoi(myStr.c_str())
Convert int to string: std::string myStr = myInt.to_string()
If you need to improve your printing format
Using printf
If using cout, you can kindve hack your way through it!
The input is a three-digit number.
If it means, you'll be given a number that will always have 3 digits, then you can try the following approach.
Separate each digit
Find all digits sum
Divide the sum by 3
If you're given the number as a string, all you've to do is convert that string into int. Rest of the approach is the same as abve.
Sample code:
int main()
{
int a;
std::cin >> a;
int sum = (a % 10); // adding 3rd digit
a /= 10;
sum += (a % 10); // adding 2nd digit
a /= 10;
sum += (a % 10); // adding 1st digit
std::cout << (double)sum / 3.0 << std::endl;
return 0;
}
Here's a possible solution using std::string:
EDIT added digits check
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s;
std::cin >> s;
if(s.length() == 3 && isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]))
{
std::cout<<double(s[0] + s[1] + s[2])/3 - '0'<<std::endl;
}
else
{
std::cout<<"Wrong input"<<std::endl;
}
return 0;
}

Output is correct but SPOJ gave me wrong answer

Quick question. This is the code that I wrote to finish a problem in SPOJ. The output is correct but it gives me wrong answer. Whats wrong with my code? This is the link to the question: https://www.spoj.com/problems/SUMUP/
#include <iostream>
#include <iomanip>
using namespace std;
void cal(int n){
long double a, b, c;
a = (n*n) + n;
b = 2.0 *(n*n + n + 1.0);
c = a / b;
cout<< setprecision(5) << c << '\n';
}
int main()
{ int n, z, t;
scanf("%d", &t);
const int NUMS = t;
int bobo[NUMS];
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
return 0;
}
This is the input:
5
1
2
3
4
5
This is my output:
0.33333
0.42857
0.46154
0.47619
0.48387
In the lines:
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
You should use z instead of n when calling scanf() and cal()
SPOJ expected output seems to require trailing zeroes, which the setprecision(5) function removes from c output if there's any. To keep the trailing zeroes you can add left << setfill('0') << setw(7) in your cout to indicate that there should be at least 7 characters presents in your output line (two characters for '0.' and 5 decimal places) and if there're fewer characters, it will fill to the left side with '0's, adding back the trailing zeroes required.
cout << left << setfill('0') << setw(7) << setprecision(5) << c << '\n';
Another more elegant solution is to use printf instead
printf("%.5Lf\n",c);
void cal(int n){
long double a, b, c;
a = (n*n) + n;
b = 2.0 *(n*n + n + 1.0);
c = a / b;
printf("%.5Lf\n",c);
}

C++ simple string parsing and save to ints

I have a string that look like this,
x:12812Y:121Z:1292
where there is always "X:","Y:", and "Z:"
I need to convert the numerals following each letter into a int variable, thus
int x = 12812
int y = 121
int y = 1292
Is there a way to do it?
Thanks!
Yes there is a way to do it:
Read two characters (the X: part), then read an integer. Repeat two more times.
If the "string" is in a file, I first recommend you read the whole line from the file into an std::string (using e.g. std::getline), then use std::istringstream to extract the data of each line.
If the order of the data is not fixe (e.g. X may not always be first) then check the first character to see what data the number is.
If the order is always fixed and the same, you can also store the number in an array or a vector.
using standard scanf is as simple as this:
#include<cstdio>
int main() {
int x, y, z;
char xx, yy, zz;
scanf("%c:%d%c:%d%c:%d", &xx, &x, &yy, &y, &zz, &z);
printf("%d %d %d\n", x, y, z);
return 0;
}
If the order and format is always fixed you could do something like this:
string str="x:12812Y:121Z:1292";//you might want to convert this to uppercase first
string xword,yword,zword;
istringstream ss(&str[1]);//put the string read in to string stream, jump the first x
//you may want to this in a loop
::getline(ss,xword,'Y');//will getthe x part,something like :12812
::getline(ss,yword,'Z');//get the y part, the y will not be read here, something like :121
::getline(ss,zword,'X');//get the z part
xword.erase(0,1);//remove the leading colon
yword.erase(0,1);//remove the leading colon
zword.erase(0,1);//remove the leading colon
// convert the string to int
Try this:
#include<iostream>
#include<sstream>
#include<string>
int main()
{
std::string str = "x:12812Y:121Z:1292";
std::string::size_type sz;
std::stringstream ss(str);
char tmp;
int x, y, z;
ss>>tmp;
ss>>tmp;
ss>>x;
ss>>tmp;
ss>>tmp;
ss>>y;
ss>>tmp;
ss>>tmp;
ss>>z;
std::cout<<"x:"<<x<<"\n";
std::cout<<"y:"<<y<<"\n";
std::cout<<"z:"<<z<<"\n";
return 0;
}
Output:
x:12812
y:121
z:1292
Some things can be done surprisingly elegantly without relying on a library.
This code demonstrates using the next_int function. next_int only takes up 9 lines -- the rest of the code demonstrates use with wide-character C-string, a char C-string and a std::string (through a C-string from std::string::c_str()).
#include <iostream>
#include <string>
// next_int parses a non-negative decimal integer value
// beginning at or after the passed string pointer.
// The pointer is incremented to point to the character
// which follows the parsed digits.
// If no digits follow the passed pointer, a value of
// zero is returned and the pointer is advanced to the
// string's terminating nul.
template <typename C>
inline int next_int(const C* &p) {
while(*p && (*p < C('0') || *p > C('9'))) { ++p; }
int val = 0;
while(*p >= C('0') && *p <= C('9')) {
val = val * 10 + *(p++) - C('0');
}
return val;
}
int main() {
const auto* pws = L"x:12812Y:121Z:1292";;
int x = next_int(pws);
int y = next_int(pws);
int z = next_int(pws);
std::cout << "(" << sizeof(*pws) << " Wide String) x: " << x << " y: " << y << " z: " << z << '\n';
const char* pcs = "54321,891011,0,1";
std::cout << "\n* char String\n";
for(int index=0; *pcs; ++index) {
const int value = next_int(pcs);
std::cout << " " << index << ": " << value << '\n';
}
// This example shows what happens when no digits follow the pointer
// passed to next_int. Because no digits appear in the characters
// following the final "10", the last call to next_int returns 0.
// next_int could be modified to unambiguously enumerate arbitrarily-sized
// sets of numbers, possibly by returning a magic number (like -1) if
// val was never updated by a digit, or adding a second scan, advancing
// p to the next digit or nul character, thus skipping the phantom
// parse at the end.
std::string nums = "Flight 552 to Paris cost me $400 1-way and lasted 10 hours";
const auto* pstr = nums.c_str();
std::cout << "\n* char String from std::string\n";
std::cout << " The extra 0 at the end comes from passing next_int a string containing no digits\n";
for(int index=0; *pstr; ++index) {
const int value = next_int(pstr);
std::cout << index << ": " << value << '\n';
}
}
This is the output:
(2 Wide String) x: 12812 y: 121 z: 1292
* char String
0: 54321
1: 891011
2: 0
3: 1
* char String from std::string
The extra 0 at the end comes from passing next_int a string containing no digits
0: 552
1: 400
2: 1
3: 10
4: 0
Assuming that keys are case-sensitive letters, values are always integers and relationship between key and value is important, but order of key/value pairs is not.
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::istringstream ss("x:12812Y:121Z:1292");
int x, Y, Z;
while (!ss.eof())
{
char tag, delim;
int val;
ss >> tag >> delim >> val;
switch(tag)
{
case 'x': x = val; break;
case 'Y': Y = val; break;
case 'Z': Z = val; break;
}
}
std::cout << "parsed: x=" << x << " Y=" << Y << " Z=" << Z << std::endl;
return 0;
},

Output not as expected from the array

I am writing a code where I take user user text input, convert it to binary, store each binary character in an element in an array and then print A or T for 0 and G or C for 1 at random. But the ATGC seem to not follow this rule and they come at random for every digit; 0 and 1. So If the binary is 0010101 I need output as ATGACTG. Also when I store the binary in an int variable, the zero in front of it vanishes. Is there a way to keep it?
#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <ctime>
int main()
{
using namespace std;
int p, i=0, a[100000];
int s;
string myString;
int binary;
cout << "Type your text: ";
std::getline (std::cin,myString);
for (std::size_t k=0; k < myString.size(); ++k)
{
std::bitset<8> y(myString[k]);
std::string dna = y.to_string();
binary = atoi(dna.c_str());
cout << binary;
while (binary != 0)
{
a[i] = binary % 10;
binary = binary / 10;
i++;
}
}
std::cout << std::endl;
srand(time(0));
for (int j = (i-1); j>-1; j--)
{
if (a[j] == 0)
{
p = rand() %2;
if (p==0)
cout<< "A";
else
cout<< "T";
}
if (a[j] == 1)
{
s = rand() %2;
if (s == 0)
cout<< "G";
else
cout<< "C";
}
else
{
cout << "";
}
}
}
I don't know why exactly you wrote so much wrong code, but I've managed to extract (and change) the code that actually does the job.
#include <iostream>
#include <string>
#include <bitset>
#include <ctime>
int main()
{
int i = 0, a[8];
std::string myString;
std::cout << "Type your text: " << std::endl;
std::getline(std::cin, myString);
for(auto x : std::bitset<8>(myString).to_string())
a[i++] = x == '1';
std::cout << std::endl;
srand(time(0));
for(int j = 0; j < i; ++j)
if(a[j] == 0)
std::cout << (rand() % 2 ? "T" : "A");
else if(a[j] == 1)
std::cout << (rand() % 2 ? "C" : "G");
std::cout << std::endl;
}
And here's neater version of main:
int main()
{
std::vector<int> a; // using std::vector
std::bitset<8> bs;
std::cout << "Type your text: " << std::endl;
std::cin >> bs; // std::bitset can be read from stream via operator>>
for(auto x : bs.to_string())
a.push_back(x == '1');
std::cout << std::endl;
srand(time(0));
for(auto x : a)
if(x == 0)
std::cout << (rand() % 2 ? "T" : "A");
else if(x == 1)
std::cout << (rand() % 2 ? "C" : "G");
std::cout << std::endl;
}
Just ask if you want an explanation on some specific part.
I told you not to convert the string to an integer. You didn't listen. This is why leading 0 vanishes.
Your output seams to be completely random because you reverse the order of characters in the sequence when reading the information from a.
Here is how I'd solve your problem: run online
#include <iostream>
#include <string>
#include <bitset>
#include <ctime>
#include <cstdlib>
int main()
{
std::cout << "Type your text: " << std::endl;
std::string in_str;
std::getline(std::cin, in_str);
std::string binary_str;
for(int i = 0; i < in_str.size(); ++i)
{
char c = in_str.at(i);
binary_str.append(std::bitset<8>(c).to_string());
}
std::cout << binary_str << std::endl;
srand(time(0));
for(int i = 0; i < binary_str.size(); ++i)
{
char c = binary_str.at(i);
if(c == '0')
std::cout << (rand() % 2 ? "T" : "A");
else
std::cout << (rand() % 2 ? "C" : "G");
}
std::cout << std::endl;
}
If you have any questions, ask me in the comments.
Edit: the OP asked me to explain all mistakes in his program.
Where did all those zeros gone?
To answer this question I'll have to explain all things your program does line-by-line.
Here you convert a symbol to a bitset:
std::bitset<8> y(myString[k])
For example: if k is 'a', then the y would be 01100001.
Here you convert the bitset to a string:
std::string dna = y.to_string();
In our example the dna would be "01100001".
Here you convert the string to an integer:
binary = atoi(dna.c_str());
A very simplified version of what atoi does:
binary = 0;
for(int i = 0; i < dna.size(); ++i)
binary = binary * 10 + (dna.at(i) - '0')
In our example the binary would be 1100001.
Note: that's NOT where you loose zeros. At this point you are still able to extract them because you know that you need to extract 8 digits. So you can append leading zeros to up it's length to 8.
The next line is where you actually loose zeros the first time because cout doesn't know that you want to print 8 digits.
cout << binary;
In our example it would print 1100001.
And here you loose zeros again because you stop extracting digits as soon as binary == 0 even if you extracted less than 8 digits. Also note that you are actually reversing what the function atoi just did with the only difference that you don't get your leading zeros back and the reverse order of bits (see the next paragraph):
while (binary != 0)
{
a[i] = binary % 10;
binary = binary / 10;
i++;
}
Why the output is "random"?
Here you are iterating through myString in the standard order
for (std::size_t k=0; k < myString.size(); ++k)
e.g. if myString is "abc" than
in the first iteration myString[k] would be 'a'
in the second iteration myString[k] would be 'b'
in the third iteration myString[k] would be 'c':
But in this loop you extract digits in reverse order:
while (binary != 0)
{
a[i] = binary % 10;
binary = binary / 10;
i++;
}
eg if binary is 1100001
in the 1st iteration you extract 1 and binary becomes 110000
in the 2nd iteration you extract 0 and binary becomes 11000
in the 3rd iteration you extract 0 and binary becomes 1100
in the 4th iteration you extract 0 and binary becomes 110
in the 5th iteration you extract 0 and binary becomes 11
in the 6th iteration you extract 1 and binary becomes 1
in the 7th iteration you extract 1 and binary becomes 0
Now you end up with an array where bits inside a character code are reversed, but different characters are stored in the array in the normal order.
e.g. If the input string was "abc", then a would become:
1,0,0,0,0,1,1, 0,1,0,0,0,1,1, 1,1,0,0,0,1,1
reversed 'a' reversed 'b' reversed 'c'
If you iterate through a in normal order, the order of bits inside character codes would be reversed. If you iterate through a in reverse order, you get the reversed order of characters.
As a rule of thumb: don't program by guessing, program by thinking.
Further reading
The Zen of Python. Most of this aphorisms are applicable to every programming language with the exception of Brainfuck
Raw C arrays are evil

How to use string.substr() function?

I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
string a;
cin >> a;
string b;
int c;
for(int i=0;i<a.size()-1;++i)
{
b = a.substr(i,i+1);
c = atoi(b.c_str());
cout << c << " ";
}
cout << endl;
return 0;
}
If I am correct, the second parameter of substr() should be the length of the substring. How about
b = a.substr(i,2);
?
As shown here, the second argument to substr is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.
Your line b = a.substr(i,i+1); will generate, for values of i:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Another interesting variant question can be:
How would you make "12345" as "12 23 34 45" without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
substr(i,j) means that you start from the index i (assuming the first index to be 0) and take next j chars.
It does not mean going up to the index j.
You can get the above output using following code in c
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char *str;
clrscr();
printf("\n Enter the string");
gets(str);
for(int i=0;i<strlen(str)-1;i++)
{
for(int j=i;j<=i+1;j++)
printf("%c",str[j]);
printf("\t");
}
getch();
return 0;
}
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
The string constructor can be used to get a copy of a substring.
string(const string& str, size_t pos, size_t n)
For example...
b = string(a, i, 2); // substring of a from position i, including 2 characters
This differs from substr in that the length n cannot be omitted. I offer this only as an alternative, not as an improvement.