C++ Help


Spadoof

Member
Joined
May 11, 2007
Messages
198
Location
Outer Heaven!
Website
Visit site
Dear readers,

I am having trouble with a C++ and I was wondering if anyone could help. I feel semi-ashamed writing this post because it seems like it should be so simple but its not clicking in my head. For a class I am currently attending, we are supposed to take a file full of poorly written code, figure out what it is supposed to do and rewrite it to be clear and working properly. Here is the code:

#include <iostream>
int main()
{
std::cout << "Enter values, control-d to quit:";
int s=0;
int c=0,limit=100;
int i;
while(std::cin>>i)
{s=s+i;
c=c+1;
}if(c!=0)
{
double a=s/c;
std::cout<<"s"<<c
<<"is"<<s
<<"ave"<<a
<<"\n";
return 0;
}
else
{
std::cout<<"No values input.\n";
return 1;
}
}

If anyone has a clue as to what this is supposed to to do, please tell me. Sorry for bothering you guys with an this kind of post. I appriciate your help.

-Spadoof :gp2x
 
Last edited by a moderator:
It's supposed to teach you how to format and read C++.

CODE

linus@beavis ~ $ cat cplus.cpp
#include <iostream>

int main()
{
int sum = 0, count = 0, i;

std::cout << "Enter values, control-d to quit:";
while( std::cin >> i )
{
sum = sum + i;
count++;
}

if ( count )
{
double average = sum / count;
std::cout << "Sum of the " << count << " numbers input is " << sum << " with an average of << average << "\n";
}
else
{
std::cout << "No values input.\n";
}
return 0;
}
linus@beavis ~ $ g++ cplus.cpp
linus@beavis ~ $ ./a.out
Enter values, control-d to quit:9
4
6
3
6
3
2
1
8
-20
Sum of the 10 numbers input is 22 with an average of 2



Sphinxter: Your indentation shows up much better when you place the code in code tags. Hope you don't mind me editing your post to do this. - Squidge
 
Last edited by a moderator:
Would putting 'using namespace std;' under the #include line help at all? Then instead of using 'std::cin' for example, you could just use 'cin'.

Correct me if i'm wrong, im not extremely experienced in C++.
 
Last edited by a moderator:
Adding 'using namespace std' in your code is frowned upon in many places now as it drags everything in the std namespace into the global namespace. So a lot of people like to specify the namespace directly each time.

Course, each person has there own coding style and all.
 
Last edited by a moderator:
'Squidge' said:
Adding 'using namespace std' in your code is frowned upon in many places now as it drags everything in the std namespace into the global namespace. So a lot of people like to specify the namespace directly each time.

Course, each person has there own coding style and all.
Ah.. I was self-taught to put using namespace std into one of the first lines..
 
Last edited by a moderator:
Back
Top