i want to take a 1000 digit integer input all at a time,& want to add the digits separately.is there any input method to take such a large input?
You need to input that as a string. Split them, and convert each character to an integer. Add them up, and you're done.
Example, this number here (randomly generated):
9624526619162264306083309360203157186784123851390498919674886891002552146753945797326679482200717699585297042606470048297021049209667042255911984240697992738371633115195140494325737382583412562136836759072897211537655046343769659111215754043609344618490646811291135643554115350431099553593485744944746093896695837300975718819726339233383800764568364950577294931831936979504756278187812548901366714205562309364234394802723329400976924082450161974562063268243689930750925213262044910428021004262080895556879515597779404780565380480750286553508081070834339176079062215815331059349488936312244526697733596052063044560959189161656978673936732284706841120711543620038686227462170335634371808995466024671420024705248851244350701111587608201303840696489479021196275228499780922745352396928865910631672384263395712487735712098161853665189905194589355110620257494673972892816413534347360049692019184831019218764766067298983043791063184786671132332077197148683743991683245617836086353821268720434176862469084808
And here's the C++ program:
int strint(std::string &str) {
int i;
std::stringstream intstr(str);
intstr >> i;
return i;
}
int main () {
std::string strdigit, schar;
int sum = 0;
std::cout << "Enter Digits: ";
std::cin >> strdigit;
std::stringstream ss;
for (int i = 0; i < strdigit.length(); i++) {
ss.clear();
ss << strdigit[i];
ss >> schar;
sum += strint(schar);
}
std::cout << sum;
}
The sum is: 4479
Simply read the digits into a string and use std::accumulate. For example:
std::string str("1234567890"); // your number here
int result = std::accumulate(str.begin(), str.end(), 0, [](int val, char ch)
{
return val + (ch - '0');
});
std::cout << result << '\n'; // display the answer
You need a library to provide support for this.
Read the digits into a string and use a multiprecision math library such as GMP to do the addition. The library should have functions for converting between digit strings and the library's internal representation for numbers.
(Actually, it looks like GMP can read digits directly from an istream, so you may not even need a string.)
I'm a little unclear on the question. If you are adding the digits separately, then I would have thought you were treating it more as a string than an integer (at least, until you start adding up the digits).
Can you clarify how the 1,000-digit integer needs to be stored in memory?
As marlon suggested, why not simply use good 'ol for loop and string?
int main() {
string str = "3985792792679283635";
int len = str.length();
int sum = 0;
for(int i = 0; i < len; i++) {
sum += str[i] - '0';
}
cout << sum << endl;
}
Related
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;
}
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;
}
This is a snippet of my code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h> // atoi()
int main() {
std::string line;
std::ifstream numbers("numbertest.txt");
if (numbers.is_open()) {
while (std::getline(numbers, line)) {
for (int i = 0; i < line.length() - 4; i++) {
for (int n = 0; n < 5; n++) {
std::cout << atoi((line.substr(i, 5)[n]).c_str());
}
I want to operate with numbers in groups of 5, from a file. Why is atoi() not working here? It says "expression must have class type" under the second parentheses on the atoi line.
line.substr(i, 5) creates a temporary std::string containing 5 characters in line from position i
std::string foo = "hello world";
int i = 2;
std::cout << foo.substr(2, 5) << '\n';
would print "llo wo".
The [n] operator returns the nth character of the substring, which is of type char, you are then calling .c_str() on that character rather than on the substring.
You can avoid the .c_str() entirely by using std::stoi, e.g.
std::cout << "line.substr(i, 5) = " << line.substr(i, 5) << '\n';
std::cout << std::stoi(line.substr(i, 5));
aoti and stoi both take a string representation of a number as their input and return the numeric value. For example:
std::string input = "123a";
// std::cout << input * 10 << '\n'; // illegal: input is a string, not a number.
int i = std::stoi(input); // converts to integer representation, i.e. 123
std::cout << i * 10 << '\n'; // outputs 1230
----- EDIT -----
You're actually asking all the wrong questions. What you want to do is take an input pattern and output all of the patterns of 5 characters in it.
Example input: "1020304050"
Example output: 10203 02030 20304 03040 30405 04050
You don't need to convert these to numbers to output them, you can just output the characters. The problem with your original code wasn't the conversion it was the incorrect sequence of operators.
std::substring is expensive, it has to create a new, temporary string, copy characters from the original into it, and then return it, and it does it for every call.
The following should achieve what you're trying to do:
while (std::getline(numbers, line)) {
for (size_t i = 0; i < line.length() - 4; i++) {
for (size_t n = 0; n < 5; n++) {
std::cout << line[i + n];
}
std::cout << '\n';
}
}
If you really want to invoke substr, you could also implement this as
while (std::getline(numbers, line)) {
for (size_t i = 0; i < line.length() - 4; i++) {
std::cout << line.substr(i, 5) << '\n';
}
}
Here's a working demonstration: http://ideone.com/mXv2z5
Try atoi( line.substr(i,5).c_str() )
Or if you want for each character
std::cout << ((line.substr(i, 5)[n]) - '0');
Or even better
std::cout << (line[i+n]) - '0');
Note that: atoi is not ascii to integer. It converts a ctype string to number. For a single character, this conversion should be done using arithmetic or lookup table.
Also there is no point converting characters to integer and then print it (back to chacters). You should better print digit character itself.
Moreover in C++, I would prefer to use stringstream instead or atoi. On C++11 there are even more advanced solutions like sto*.
I have a large number in c++ stored as a precise double value (assuming the input 'n' is 75): 2.4891e+109
Is there any way to convert this to a string or an array of each individual digit?
Here's my code so far, although it's not entirely relevant to the question:
int main(){
double n = 0;
cout << "Giz a number: ";
cin >> n;
double val = 1;
for(double i = 1; i <= n; i++){
val = val * i;
}
//Convert val to string/array here?
}
std::stringstream str;
str << fixed << setprecision( 15 ) << yournumber;
You may also be interested in the scientific format flag.
C++11 also has a few interesting functions std::to_string which you may want to check out!
What's wrong with the standard way?
std::stringstream ss;
ss << val;
std::string s = ss.str();
Additionally, C++11 allows:
std::string s = std::to_string(val);
If you need performance you might find that the memory allocations involved above are too expensive, in which case you could resort to snprintf, the deprecated strstream, or perhaps direct use of the num_put facet. For example:
char c[30];
std::snprintf(c,sizeof c,"%e",val);
You will find that the double value is not as precise as you think. It only contains 53 bits of precision, or about 15-17 digits; after that it starts rounding each result. Your number requires much more precision than that if you want an exact answer, 92 digits actually or 364 bits.
std::cout << setprecision(5) << val;
as in http://www.cprogramming.com/tutorial/iomanip.html
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;