int and string parsing - c++

If i have a int say 306. What is the best way to separate the numbers 3 0 6, so I can use them individually? I was thinking converting the int to a string then parsing it?
int num;
stringstream new_num;
new_num << num;
Im not sure how to do parse the string though. Suggestions?

Without using strings, you can work backwards. To get the 6,
It's simply 306 % 10
Then divide by 10
Go back to 1 to get the next digit.
This will print each digit backwards:
while (num > 0) {
cout << (num % 10) << endl;
num /= 10;
}

Just traverse the stream one element at a time and extract it.
char ch;
while( new_num.get(ch) ) {
std::cout << ch;
}

Charles's way is much straight forward. However, it is not uncommon to convert the number to string and do some string processing if we don't want struggle with the math:)
Here is the procedural we want to do :
306 -> "306" -> ['3' ,'0', '6'] -> [3,0,6]
Some language are very easy to do this (Ruby):
>> 306.to_s.split("").map {|c| c.to_i}
=> [3,0,6]
Some need more work but still very clear (C++) :
#include <sstream>
#include <iostream>
#include <algorithm>
#include <vector>
int to_digital(int c)
{
return c - '0';
}
void test_string_stream()
{
int a = 306;
stringstream ss;
ss << a;
string s = ss.str();
vector<int> digitals(s.size());
transform(s.begin(),s.end(),digitals.begin(),to_digital);
}

Loop string and collect values like
int val = new_num[i]-'0';

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;
}

Print number as number in string type

I have the following code :
string a = "wwwwaaadexxxxxx";
Intended Output : "w4a3d1e1x6";
somewhere in my code I have int count = 1; ... count++;
Also, somewhere in my code I have to print this count as a[i] but as a number only .. like 1,2,3 and not the character equivalent of 1,2,3.
I am trying the following : printf("%c%d",a[i],count);
i also read something like :
stringstream ss;
ss << 100
What is the correct way to do so in CPP?
EDIT :
so i Modified the code to add a number at index i in a string as :
stringstream newSS;
newSS << count;
char t = newSS.str().at(0);
a[i] = t;
You can use a stringstream to concatenate the string and the count,
stringstream newSS;
newSS << a[i] << count;
and then finally convert it to string and then print it or return (if this is done inside a function)
string output = newSS.str();
cout << output << endl;
But if your objective is only to print the output, then using the printf is fine.
If you need to update in place, then you can use two pointers. Let them be i,j.
You use j to set the new value and i to count the count. This is the standard runLength Encoding Problem.
There is no "correct" way. You could use snprintf, stringstream, etc. Or you could roll your algorithm. Assuming this is a base 10 number, you want the number in base 10.
#include <iostream>
#include <string>
#include <algorithm>
int main(void)
{
int a = 1194;
int rem = 0;
std::string output;
do {
rem = a % 10;
a = a / 10;
output.append(1, rem + '0');
} while(a != 0);
std::reverse(output.begin(), output.end());
std::cout << output << std::endl;
return 0;
}

Counting and getting highest number of digits after decimal

I want to get a count of highest number of digits from an array of decimal numbers.
For example, between 2.1 and 2.01, the resultant counter should be 2 since there are 2 digits after 2.01.
Can anyone please help me with this?
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
double z[100],x[100],sml;
int count=0,i=0,n;
cout<<"ENter number of elements\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>z[i];
}
x[0]=z[0]-int(z[0]);
i=0;
for(i=0;i<n;i++)
while(z[i]>=0.001&&i<n)
{
x[i]=z[i]-int(z[i]);
i++;
}
for(i=0;i<n;i++)
{
cout<<x[i]<<"\t";
}
sml=x[0];
for(i=0;i<n;i++)
if(sml>x[i])
sml=x[i];
sml=sml-int(sml);
while(sml>=0.001)
{
sml=sml*10;
count++;
sml=sml-int(sml);
}
cout<<endl<<count;
return 0;
}
It's not impossible, it should be pretty easy actually. Cast it to a string, get the substring of the results starting at the decimal and count the result.
For this you will need to look up:
-casting
-indexof
-substring
If you give it a try and can't figure out comment and I will offer you a little more guidance but you should try it yourself first.
EDIT:
I don't see much of an attempt to do what I suggested, it looks like you just posted the code you had. So here is some pseudo code for you to work with:
string stringNum = to_string(decimalNum);
int decimalPos = stringNum.find(".");
string newString = stringNum.substr(decimalPos);
int answer = newString.length();
I pretty well answered it for you, you need to figure out the syntax.
just go ahead and use this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
float number[] = {1.234,5.64,2.001,7.11112,3.999};
int a,numAfterDecimal = 0;
for(a=0;a<sizeof(number)/sizeof(*number);a++){
ostringstream buff;
buff<<number[a];
string numStr= buff.str();
int pos = numStr.find(".");
string floatStr = numStr.substr(pos+1);
if(a == 0){
numAfterDecimal = floatStr.length();
}
else if(floatStr.length() > numAfterDecimal){
numAfterDecimal = floatStr.length();
}
}
cout << " higest number of digit after decimal is:"<< numAfterDecimal <<endl ;
}
Answer is already accepted. But just for the fun of it. Here a solution using C++ algorithms.
This will reduce the number of statements in main drastically.
Maybe it helps you to better understand modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
inline size_t getNumberOfDigitsForFraction(const std::string& s)
{
size_t positionOfDecimalPoint = s.find("."); // Look for decimal point
// And count the numbers of digits after the decimal point
return positionOfDecimalPoint == std::string::npos ? 0 : s.substr(positionOfDecimalPoint+1).size();
}
int main()
{
std::cout << "Enter the number of elements that you want to check: ";
size_t numberOfElementsToCheck{0};
// Read how many data the user wants to process
std::cin >> numberOfElementsToCheck;
// Hier we will store the values
std::vector<std::string> elements(numberOfElementsToCheck);
// Copy all wanted values from std::cin
std::copy_n(std::istream_iterator<std::string>(std::cin),numberOfElementsToCheck,elements.begin());
// Get the Element with maximum digits and print the number of digits
std::cout << "Max number of digits following decimal point: " <<
getNumberOfDigitsForFraction(
*std::max_element(elements.begin(), elements.end(),
[](const std::string &sLeft, const std::string &sRight)
{ return getNumberOfDigitsForFraction(sLeft) < getNumberOfDigitsForFraction(sRight);} )) << '\n';
return 0;
}

How do I reverse the output of a program?

I have to convert decimal numbers like 43.62 to binary. So i first wrote a basic program that converts 43 into binary. But I notice that my program prints out the binary number in reverse, so it prints 1 1 0 1 0 1 instead of 1 0 1 0 1 1. how can I fix this.
My Code:
#include <iostream>
using namespace std;
int main()
{
int number;
int remainder;
cout << "Enter a integer: ";
cin >> number;
while(number != 0)
{
remainder = number % 2;
cout << remainder << " ";
number /= 2;
}
int pause;
cin >> pause;
return 0;
}
Instead of sending each digit to cout, send them to an array. Then read the array out in reverse order. Or push them onto a stack, and then pop them back off the stack. Or...
Something of a sledgehammer to crack a nut, but here's a solution based on a recursive approach:
#include <iostream>
using namespace std;
void OutputDigit(int number)
{
if (number>0)
{
OutputDigit(number /= 2);
cout << number % 2 << " ";
}
}
int main()
{
OutputDigit(43);
return 0;
}
You can get the same output as you had before by simply moving the cout one line up!
Look at vector and think about how it could be useful to save the remainders instead of printing them right away.
Notice that you don't have to put things at the end of the vector. vector::insert lets you specify a position... could that be helpful?
Alternatively, the algorithm you created starts at the least significant digit. Is there a way to start from the most significant digit instead? If I have the number 42 (0101010), the most significant digit represents the 32s, and the 0 ahead of it represents the 64s. What happens if I subtract 32 from 42?
It would be easier to store the results and then print them backwards. Using recursion is also another possibility to do just that.
Most significant bit first:
const unsigned int BITS_PER_INT = CHAR_BIT * sizeof(int);
char bit_char = '0';
for (int i = BITS_PER_INT - 1;
i > 0;
--i)
{
bit_char = (value & (1 << i)) ? '1' : '0';
cout << bit_char << ' ';
}
cout << '\n';
cout.flush();
To print least significant bit first, change the direction of the for loop.
In C++, you can also use a bitset container to do this,
#include <bitset>
int i = 43;
std::bitset<sizeof(int)*CHAR_BIT> bin(i);
Just use string functions
string s ;
while(number != 0)
{
remainder = number % 2;
string c = remainder ? "1": "0";
s.insert(s.begin(),c.begin(),c.end());
number /= 2;
}
When you do such conversion by holding on to the remainder, the result will always be reverted. As suggested use bitwise &:
unsigned char bit = 0x80; // start from most significant bit
int number = 43;
while(bit)
{
if( bit & number ) // check if bit is on or off in your number
{
cout << "1";
}
else
{
cout << "0";
}
bit = bit >>1; // move to next bit
}
This example will start going through all your 8 bits of the number and check if the bit is on or off and print that accordingly.
Best option - Use C++ stringstream for formatting I/O
// Add the following headers
#include <sstream>
#include <algorithm>
// your function
stringstream ss;
// Use ss in your code instead of cout
string myString = ss.str();
std::reverse(myString.begin(),myString.end());
cout << myString;

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.