• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ Programming question

TGCid

Platinum Member
I am starting a AP Computer Science class and I am kinda stuck on how to do this program. The program is to grab a series of number entered by a user seperated by whitespace and square them then display it on the screen. I cannot assume the number of number the user going to input (this is the hard part for me). I was thinking of maybe grabbing the entire line and output it to a file then read back and square each one separately. I seriously am stuck since it has been kinda a long summer and the Intro to C++ teacher sucks really really bad. In fact, she got fired and we got a new teacher (oh joy) who never taught C++ in a longg time. So please give me some ideas on what to do. Thanks a whole bunch!!
 
why dont you just prompt the user how many numbers he want to enter? otherwise you should just have the preset number of numbers...
 
have you covered the linked lists yet?
for dynamically deteremined # variables pointer based apporoach is the way to go.
otherwise you could use arrays (apvector)
 
nah...you won't need any linked list or array..
just read them one by one, and compute the square,
and print the result....then do the same for the next one
(basically read them in the loop).

You need to find out how the user end the input,
you might want to try to capture that special character
(might be \n, \0 or whatever), and use that to end
the loop.

or you can always try the following code (in C though,
but works for C++)

while (scanf("%d", &i))
printf("i squared = %d\n", i*i);
 
If I prompt the user for the amount of numbers he/she going to enter, how would i code it to declare that much variable to store?
I don't think i am allow to do this by the way, but gotta start somewhere.

No we haven't even got to the APvector thing yet, teacher is not really helping either.
Brown,
How would I just grab part of the line, then start grabbing the next?

Thanks for the inputs so far guys/gals.
 
the solution is quite trivial, all you need to do is to dynamically allocate and reallocate memory...this is kinda ugly because i did it rather fast but you'll get the idea. Also check for possible UMRs and UMWs (Uninitialized Memory Reads and Writes) and ABW/Rs (array bound read write errors), because i have no tools on me to check for that 🙂

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
char c;
unsigned int numLines = 5;
char **buffer = new char*[numLines]; // assume some number of lines
for(int j=0; j<numLines; j++)
buffer[j] = NULL; // not necessary on UNIX based systems, dunno on Win32

int countChar = 0; // counters
int countStrs = 0;
int allocated = 0; // counter of allocated memory for the line

while((c = getchar( )) != EOF) // main loop
{
if(isdigit(c) || c == '.') // check if its a digit or a floating point number
{
countChar++;
if(countChar > allocated) // do we need to reallocate memory?
{ // yes
allocated += 3; allocated *= 3; // i like number 3 🙂
if(buffer[countStrs]) // check if buffer[countStrs] was allocated
{
char tmp[allocated];
strcpy(tmp, buffer[countStrs]); // copy over the contents
delete [] buffer[countStrs]; // free the old memory
buffer[countStrs] = new char[allocated]; // allocate new memory
strcpy(buffer[countStrs], tmp); // copy over the contents
}
else // first time initialization
buffer[countStrs] = new char[allocated];
} // no
*(buffer[countStrs]+countChar-1) = c; // stick the current char in the line
*(buffer[countStrs]+countChar) = '\0';
}
else if(c == ' ' || c == '\n') // white space divides the numbers
{
if(!buffer[countStrs]) // if anything else besides a digit or a &quot;.&quot; is received ignore it and move down the line pointer
{
countStrs--; // was didn't wright anything last time so we can try reset the pointer to the prevoius location
}
countStrs++; // up the line count
if(countStrs >= numLines) // check if need to reallocate memory for the lines
{
numLines *= 2; // i like 2 too 🙂
char **tmp = new char*[numLines]; // allocate more memory
for(int j=0; j<countStrs; j++) // copy over the conetnts
{
tmp[j] = new char[strlen(buffer[j])+1];
strcpy(tmp[j], buffer[j]);
delete [] buffer[j]; // kill old content (we could just point to the strings, but thats more &quot;correct&quot;
}
delete [] buffer; // delete od buffer
buffer = tmp; // reallocate the pointer
}
countChar = allocated = 0; // reset the char counters
if(c == '\n') // exit on end of line char
break;
}
}

for(int i=0; i<countStrs; i++)
{
if(strstr(buffer[j], &quot;.&quot😉) // it just occured to me that you can have more than 1 &quot;.&quot; per line, so you can strstr for the address just after the first &quot;.&quot; and if the result of the strstr is not NULL set that memory location to '\0'
printf(&quot;%f\n&quot;, atof(buffer[j])* atof(buffer[j]));
else
printf(&quot;%d\n&quot;, atol(buffer[j])* atol(buffer[j]));
delete [] buffer[j]; // cleanup
}
delete [] buffer; // cleanup
}

Damn, the array subscripts are all screwed up with the new html parser...all appear as itallics 🙂 i'll try to fix that
 
hmm.... i guess someone had some remarks about my program and realized he was wrong on every point, so he deleted his post 🙂

That proggy may not look simple but it really is (at least to me). All it does is allocates and reallocated memory as new digits come in, that's it.

1. It accepts floats and int as possible inputs
2. All other characters are ignored as they should be. Multiple spaces are allowed, actually there are no restrictions on the input (so input like this: &quot;sfbsdjg gf2 5 gfg dfg **-+++++- 10&quot; will result in the following output &quot;4\n25\n\100\n&quot; and all other jiberish is filtered out.
3. First character can be whatever the you want it to be 🙂 (this is in replay to the deleted post)
4. limitation on the number lenght and their numbe is dictated by...
...a) memory (size/possible fragmentation)
...b) hardware math capabilities (obvously squaring a gigant number will result in a harware overflow and the ALU will stream out an incorrect value). If you want to protect against that find out what are the ranges for doubles (long doubles) and longs on the architecture you are working on, and fiter out the results that are out of bounds.
5. It does not rely on BUFFER size nor does it make any assumptions, it will grow accordigly based on the users' request. The memory allocations are not asserted, because it's an example...industrial applications will assert the allocated memory for possible failures and catch any other thrown exceptions.
 
if he is taking a CS course at a high school, i dont think he would be using those header files. instead he might wanna use ap classes. just my 2cents.
 
Those are definition files are part of standard lib. <ctype.h> for isdigit(...) <string.h> for strstr(...), strlen(...), strcpy(...), ... and <stdlib.h> for atof(...) atol(...). I agree that that solution is a bit too advanced for an entry level (??) C++ class, but thats the simplest solution that uses dynamic memory allocation, hence is independent off the size of the input stream, and at the same time protects the users from their stupidity (the program accepts any input and filters out the number sequences) and thats what he wanted...One of Your ideas involved linked lists (why?), and the last time i checked abstract data structures are higher on the difficulty scale than both dynamic memory allocation and a few conveniance calls to standard lib. Nevetherlessm I can simplify my suggestions if TGCid wants me to.
 
HigherGround solution is too complicated and not efficient.

As I said before, you don't even need an array or linked list
to store all the inputs.

What you want to do is : Read 1 input at one time, and compute
the result, then get next input, compute the result, see you
only need storage for 1 input (as you can use it over and over).

You also don't want to grab the entire line, as you then need
to traverse the entire line.
Remember even if the user type the input in, the user need
to indicate the end of input (either by typing RETURN key or
maybe anything to indicate end of input).

Have you tried the code that I gave to you ? It assumes that
user type ^C, or ^D to end the input, and whenever the user
type RETURN, it will compute the results, it can receive
any amount of inputs (only 2 lines of code).

Or complete code is :

// CODE START

#include <stdio.h>

main()
{
int i;
while (scanf(&quot;%d&quot;, &amp;i))
printf(&quot;i squared = %d\n&quot;, i*i);
}

// CODE END

The above is simple and to the point (and actually is even harder
to figure out 😛), I don't think high school CS classes want you to
do anything more than that.

Anyway, have fun 🙂

 
or this code for asking user how many input he will enter upfront, you won't
even need array to store the inputs.

// CODE START

#include <iostream.h>

main()
{
int a, i, n;
cin >> n;

for (i=0; i<n; i++)
{
cin >> a;
cout << &quot;the squared is &quot; << a*a << endl;
}
}

// CODE END

Don't do anything too fancy, otherwise the teacher won't
appreciate it.

If I were to teach highschool, I would expect a clean and
simple solution, instead of using some ADVANCED TECHNIQUES.


edit : All the two solutions above, grab part of the input
until whitespace, then compute the result, then grab another one.
Remember if you use cin, or scanf, these functions automatically
grab input until whitespace is detected, thus you don't need
to implement anything fancy at all to detect whitespace.

If you want to handle floating points, just change int to float
or double as simple as that.
 
Thank you so much guys. I will mess around with the code some more and take your advice. This is such a major transition from last year, now I really don't like last year teacher even more. She didn't prepare us very well. Again thanks.
 
What is a simple way to detect if the user is inputting letters rather than numbers? The teacher wants a foolproof as much as possible. So supposedly an idiot entered &quot;abc&quot; rather than &quot;123&quot; how would I detect such a thing and cout an error to the screen? Thanks.
 
use isdigit() functions to detect whether input is a digit or others,
you need to include <ctype.h>

Here is a sample :

// CODE START

#include <iostream.h>
#include <ctype.h>

main()
{
char a;
cin >> a;
if (isdigit(a))
cout << &quot;A is a digit\n&quot;;
else
cout << &quot;A is not a digit\n&quot;;
}

// CODE END

 
br0wn,
You are a f@cking genius. The code you gave me was so simple yet so efficient. Thank you so much.

Higherground,
Seriously, I have no clue what your code is, I am way way below your level man. Thanks anyways.

Thanks again to everybody else too. Expect more programming questions from me in the future hehe. 🙂
 
Back
Top