# Book exercise help.

This topic is 4871 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Im working through a c++ book because I haven't done any for a while and the current exercise is: Write a program that reads an interger (into a veriable of type int) and computes the sum of its final two digits. Can anyone tell me where to start on this as I have no idea.

##### Share on other sites
Does it say to explicitly read it in as an integer? It would probably be easier to read it as a char array or string and then convert the requested digits into integers.

##### Share on other sites
there are about an infinite number of ways to do it, and trying several would probably be good. I'll give you some hints.

%

itoa

bitwise

try those three

##### Share on other sites
Yes it says into a veriable of type int.

It's in the chapter Expressions and Statements but I have read nothing which helps with this exercise.

##### Share on other sites
Ok this is what I understand:

---

%

This is used to return the remainder from a division. So if "i = 11 % 3" i will equal 2.

I can't see how to solve it using this. can anyone push me in the right direction?

---

itoa()

This converts an integer to a string. So a method of solving the problem would be convert it to a string. Get the last two digits. Turn them back into an int. Add them. Would this work?

---

bitwise operators

I understand what these are and how they work (OR, AND, XOR etc.) but I can't see how they would help me get the last two digits of an interger. A push here as well?

Thanks alot.

##### Share on other sites
I agree, I don't reallysee how the Modulus operator or bitwise operators would really help. If I remember correctly, itoa is not technically part fo the C++ library, just the C library.

##### Share on other sites
hint: sum = x % 10 + x / 10 % 10;

##### Share on other sites
Quote:
 Original post by menghaOk this is what I understand:--- %This is used to return the remainder from a division. So if "i = 11 % 3" i will equal 2.I can't see how to solve it using this. can anyone push me in the right direction?---itoa()This converts an integer to a string. So a method of solving the problem would be convert it to a string. Get the last two digits. Turn them back into an int. Add them. Would this work? ---bitwise operatorsI understand what these are and how they work (OR, AND, XOR etc.) but I can't see how they would help me get the last two digits of an interger. A push here as well?Thanks alot.

What woudl be the result 145 % 10?

What would be the result of 176 % 10?

what would be the result of 210345 % 10?

the last digit?

As for the itoa i think you have the idea.

As for it being none standard I don't think it matters to much.
If you were working in MFC (non standard) you could use CString::format.
Just a tool to work with.

The bitwise... well that would be fun... the idea is to learn.

Problem solving is more important than the language.

##### Share on other sites
I have tried to complete the exercise using % and itoa and have got this far:

#include <iostream>using namespace std;int main(){ 	int iInput = 0;	int iLength = 0;	int iCount = 0;	char cBuffer[33];	char cTemp1[1];	char cTemp2[1];	cout << "Enter an integer. This program will add the last to digits together.\n\n";	cout << "Input: ";	cin >> iInput;	/* Method One */	cout << "\n\nUsing method one (%): " << (iInput % 10) + ((iInput / 10) % 10);		/* Method Two */	cout << "\nUsing method two (itoa): ";	// Convert the entry to char.	itoa(iInput, cBuffer, 10);		// Get the length of the array. (how many numbers are in it.)	iLength = strlen(cBuffer);	// I am copying the last to numbers into their own variables because when i do	// atoi(&cBuffer[iLength - 1]) when "123" was entered i get "123" back. I just want one number.	cTemp1[1] = cBuffer[iLength - 1];	cTemp2[1] = cBuffer[iLength - 2];	// Turn them back into ints and add them.	cout << atoi(&cTemp1[1]) + atoi(&cTemp2[1]);	// Pause so we can see the output.	cin >> iInput;	return 0;}

This works.

I understand how to use % more now. If i wanted the third digit in I could do ((iInput / 100) % 10)

I also managed to get the char method working. But it seems a bit weird, like me having to copy the numbers to their own variables. Is their a better way of me doing it?

I still have no idea on doing it bitwise.

Thanks :)

##### Share on other sites
First, note that your question properly belongs in For Beginners. Hate to break it to you.

Bitwise operations aren't likely to be any use to you.

For reading in a number in C++, it is best to use the tools that the library provides to you. If you can assume valid input, then just "reading into" (with operator >>) an int does all you need. However, assuming valid input is rarely a good idea ;) and it will cause serious problems with that method if you don't check for them. (It will cause entirely different problems with itoa(); if you put in a non-numeric value, it will just interpret it as 0, and you won't get a chance to test whether it really was a 0 that got entered.) See here for more info, but here is a summary of reading things in "safely" of any type:

// Note: You are responsible for finding and including the necessary libraries,// accounting for namespaces, etc.// When the available input can't be formatted as the type we're trying to read// (e.g. we ask for an int and we get "hi mom"), there are two things to worry// about:// 1) The input is NOT "read", but instead sits there so that it will be// picked up by the next read attempt. This allows you to "fall back" to// interpreting the data in a different way, although that's rarely useful.// 2) The stream will go into a "fail" state.// I will make two templated functions for grabbing an item from the specified// stream. You can put in something of any type for the second argument, and it// will work accordingly. In each of these, we will provide five arguments:// 1) The stream to read from// 2) The variable to read into (this works by "passing by reference")// 3) The stream to output prompts to// 4) The prompt message// 5) The error message// For the first version, we will skip past the current line of input and try// again each time we fail. This has the advantage that we don't have to// temporarily read and store the whole line of texttemplate <typename T>istream& readFromAtBeginning(istream& source, T& target, ostream& console, const string& prompt, const string& error) {  // At the beginning of each loop we prompt, and then try to read the target;  // if the target reading succeeds, the loop will break  while (console << prompt << endl && !(source >> target)) {    // If we get here, the reading failed    source.clear(); // reset the "failed" state    source.ignore(numeric_limits<streamsize>::max(), '\n'); // skip a line    // Then spit out an error message, and re-prompt.    console << error << endl;  }  // Allow for chaining. Actually, this isn't at all useful at the moment, but  // might become useful if you find a way to wrap this into a class ;)  return source;}// For the second version, we will read in full lines into a temporary buffer,// and parse the buffer contents. This will be slower, although it (a) won't// require any "fixing" of the input, and (b) makes it easier to add a check // (if desired) that there isn't any extra garbage at the end of the line.template <typename T>istream& readFromParsingLine(istream& source, T& target, ostream& console, const string& prompt, const string& error) {  // At the beginning of each loop we prompt, and then read the target;  // within the loop, we do the parsing.  string line; // our buffer for input  while (console << prompt << endl && source >> line) {    stringstream parser(line);    if (line >> target) {      // we succeeded in reading.      return source;    }    // Otherwise, the reading failed; we don't have to do any resetting - the    // stringstream will simply be destructed, and a new one created for the    // next line of input.    // So all we do is spit out the error message and re-prompt:    console << error << endl;  }  // Should never get here...  return source;}// I am also going to provide one more function that I think is useful: it will// save you from having to declare a variable to read into - obviously you can't// do chaining with it though (no way to specify the "links" in the chain). This // one will only make one attempt; it's intended for use e.g. with files where// prompting (or for that matter, skipping a whole line because of bad input)// is not appropriate. It will also return a default-constructed value in the// case of bad input.template <typename T>T readFrom(istream& is) {  T result = T();   if (!is >> result) { is.clear(); }  return result;}// Now you can write e.g.cout << readFrom<int>(cin) * readFrom<int>(cin) << endl;// Warning! the compiler IIRC is allowed to make the two readFrom() calls// in either order. For the '*' operator it happens not to matter, but results// are undefined e.g. with '<'.

These are not exactly functions that a beginner is likely to write for him/herself - at least not without a LOT of prompting :) However, I provide them because they provide a fairly simple solution to a common problem, and will allow for solving the problem just once - which is good, because it's an annoying one :) It will also probably provide a decent exercise in debugging, because I haven't tested any of it ;)

1. 1
Rutin
22
2. 2
3. 3
4. 4
5. 5

• 9
• 9
• 9
• 14
• 12
• ### Forum Statistics

• Total Topics
633308
• Total Posts
3011294
• ### Who's Online (See full list)

There are no registered users currently online

×