Program that shows sum of even numbers - while-loop

I have a problem for my CS class that I'm just not getting. I have to read an unspecified amount of integers in a text file. From there on I have to find the integers that are divisible by 5 and then add them up. Say I have a text file containing 1, 5, 7, 10, and 11, so my answer should be 15. The instructor says we have to use a while loop to read until End-Of-File.
Here is what I have, which is completely wrong:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int sum, even;
sum = 0;
ifstream inFile;
inFile.open("numbers.txt");
inFile >> even;
do
{
if (even % 5 == 0)
{
sum = sum + even;
cout << "\nThe sum of the numbers is:" << sum << endl;
}
else
{
cout << "\nNo numbers divisible by 5." << endl;
}
}
while (!inFile.eof());
inFile.close();
system("pause");
return 0;
}
Something does happen; an endless loop that goes through large negative numbers.
Can anyone point me into the right direction?
Thanks,
Tobi
Update: I have this so far, but it prints out 4 answers.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num, sum, count;
sum = 0;
ifstream inFile;
inFile.open ("numbers2.txt");
if (!inFile)
{
cout << "Can't open the input file.\n" << endl;
system("pause");
return 1;
}
inFile >> num;
while (!inFile.eof())
{
inFile >> num;
if (num % 5 == 0)
{
sum += num;
cout << "Sum is: " << sum << endl;
}
else
{
cout << "Is not divisible by 5." << endl;
}
}
inFile.close();
system("pause");
return 0;
}
My output looks like this:
sum is: 5
sum is: 25 (What I want as the output)
Is not divisible by 5.
Is not divisible by 5
I'll keep trying until I get this.
Thanks to everyone who has answered so far.

You can try something like this...not perfect, but just something you can use to understand and improve upon.
C++ example - program.cpp
#include <iostream> // provides cout, endl etc.
#include <fstream> // provides file stream functionality
#include <string> // provides string
#include <stdlib.h> // provides atoi functionality
using namespace std;
int main()
{
int sum = 0;
int num = 0;
bool multiple_of_5_found = false;
std::ifstream file("numbers.txt");
std::string str;
// while begins
while(std::getline(file, str))
{
// convert string to number
num = atoi(str.c_str());
if (num % 5 == 0)
{
multiple_of_5_found = true;
sum += num;
}
}
// while ends
// based on what we observed/calculated, print info
if (multiple_of_5_found)
{
cout << "The sum of numbers divisible by 5 is "
<< sum << endl;
}
else
{
cout << "No number divisible by 5" << endl;
}
return 0;
}
GCC version
$> g++ --version
g++-4.7.real (Debian 4.7.2-5) 4.7.2
numbers.txt
$ cat numbers.txt
1
5
7
10
11
15
compile and run
$ g++ program.cpp && ./a.out
The sum of numbers divisible by 5 is 30
Visual Studio 2013 screenshot of numbers.txt resource
Visual Studio 2013 screenshot of Source.cpp
Visual Studio 2013 screenshot after pressing F7 and clicking on Local Windows Debugger

Related

Why is my code exiting with code -8 although I used numbers within the maximum numeric limit<unsigned int>?

I gotta write a code that converts decimal to binary, only library header is allowed. Only numbers with <9 digits seem to work, even if unsigned int is used.
I. e. 4 billion should work but outputs code -8.
#include <iostream>
int main()
{
unsigned int n;
unsigned int i = 1;
//input
std::cout << "Input natural number:" << std::endl;
std::cin >> n;
//find highest power of 2 as divisor -> i
while(n / i != 0)
{
i *= 2;
}
if (i != 1)
i /= 2;
//outputs binary
while(i > 0)
{
std::cout << n/i;
if (n/i == 1)
n -= i;
i /= 2;
}
}

Defining strict_real_policies for reals with a comma decimal character

I would like to create a custom policy derived from strict_real_policies that will parse reals, such as "3,14", i.e. with a comma decimal point as used e.g. in Germany.
That should be easy, right?
#include <iostream>
#include <string>
#include <boost/spirit/home/x3.hpp>
template <typename T>
struct decimal_comma_strict_real_policies:boost::spirit::x3::strict_real_policies<T>
{
template <typename Iterator>
static bool
parse_dot(Iterator& first, Iterator const& last)
{
if (first == last || *first != ',')
return false;
++first;
return true;
}
};
void parse(const std::string& input)
{
namespace x3=boost::spirit::x3;
std::cout << "Parsing '" << input << "'" << std::endl;
std::string::const_iterator iter=std::begin(input),end=std::end(input);
const auto parser = x3::real_parser<double, decimal_comma_strict_real_policies<double>>{};
double parsed_num;
bool result=x3::parse(iter,end,parser,parsed_num);
if(result && iter==end)
{
std::cout << "Parsed: " << parsed_num << std::endl;
}
else
{
std::cout << "Something failed." << std::endl;
}
}
int main()
{
parse("3,14");
parse("3.14");
}

Need help in getting the process name based on the pid in aix

I need to write a C program in AIX environment which will give me the process name.
I can get the pid but not the process name based on the pid. Any specific system calls available in aix environment??
Thanks
getprocs is likely what you want. I created this under AIX 5.x.
I have a little routine that cycles thru all processes and dumps their information.
while ((numproc = getprocs(pinfo, sizeof(struct procsinfo),
NULL,
0,
&index,
MAXPROCS)) > 0 ) {
for (i = 0;i < numproc; i++) {
/* skip zombie processes */
if (pinfo[i].pi_state==SZOMB)
continue;
printf("%-6d %-4d %-10d %-16s\n", pinfo[i].pi_pid, pinfo[i].pi_uid, pinfo[i].pi_start, pinfo[i].pi_comm);
}
}
....
I realize this is an old question.
But, to convert the #CoreyStup answer into a function that more closely addresses the OP, I offer this: (tested on AIX 6.1, using: g++ -o pn pn.cc)
--- pn.cc ---
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <procinfo.h>
#include <sys/types.h>
using namespace std;
string getProcName(int pid)
{
struct procsinfo pinfo[16];
int numproc;
int index = 0;
while((numproc = getprocs(pinfo, sizeof(struct procsinfo), NULL, 0, &index, 16)) > 0)
{
for(int i=0; i<numproc; ++i)
{
// skip zombies
if (pinfo[i].pi_state == SZOMB)
continue;
if (pid == pinfo[i].pi_pid)
{
return pinfo[i].pi_comm;
}
}
}
return "";
}
int main(int argc, char** argv)
{
for(int i=1; i<argc; ++i)
{
int pid = atoi(argv[i]);
string name = getProcName(pid);
cout << "pid: " << pid << " == '" << name << "'" << endl;
}
return 0;
}

printing lines from files

I'm trying to print the first line from each file but I think its outputting the address instead.
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void FirstLineFromFile(ifstream files[], size_t count)
{
const int BUFSIZE = 511;
char buf[BUFSIZE];
ifstream *end, *start;
for (start = files, end = files + count; start < end; start++)
{
cout << start->getline(buf, sizeof(buf)) << '\n';
}
}
streams should not be passed by value. This code passes an array of streams by value. You can try to pass a vector instead and interate over them.
void FirstLineFromFile(vector<ifstream*> files) {
for (int i=0; i<files.size(); ++i) {
string s;
getline(*files[i], s);
cout << s << endl;
}
}
ifstream->getline does not return a string as its return value. You need to print out the buffer that it has filled in a separate line.
for (start = files, end = files + count; start < end; start++)
{
start->getline(buf, sizeof(buf));
cout << buf << '\n';
}

After I disable g++ return value optimization,Why the last call of constructor for temporary reference?

I compile the c++ code using the follow command to disable return value.
g++ -fno-elide-constructors rvoptimazation.cpp -o test
But the output of ./test is
10
10
10
13
0xbfdf0020
13
I am confused by the last call of the constructor. Can anyone explain which line of the code will call the constructor after return in operator*? Thanks in advance.
#include<iostream>
using namespace std;
class Rational{
public:
Rational(int x ,int y){
_a = x;
_b = y;
cout << __LINE__ << endl;
}
Rational(Rational const &t){
cout << __LINE__ << endl;
}
Rational operator*(Rational const &t){
Rational re = Rational(_a * t._a ,_b * t._b);
cout << &re << endl;
return re;
//return *this;
}
Rational get()
{
return *this;
}
public:
int _a ,_b;
};
int main()
{
Rational r1(1 ,2);
Rational r2(2 ,3);
r1 * r2;
// cout << &r3 << endl;
}
operator* returns by value, so the returned object must be constructed. The statement return re calls the copy constructor to do that.
I think the explanation at Return value optimization is quite clear.