In the output first the text " Sum is : " is getting printed and then the function is getting called. Please check this code - output

#include<iostream>
using namespace std;
int sum();
int main() {
cout << "Sum is: " << sum() << endl;
return 0;
}
int sum() {
int num1,num2;
cout << "Enter 2 numbers: " << endl;
cin >> num1 >> num2;
return (num1 + num2);
}
I am not getting a correct out put. First "Sum is: " getting called and then the function in output.
Output is given as:- "Sum is: Enter 2 numbers: " and then enter numbers. But it gives correct output. But its not coming as I want.

Your sum() function gives the "Enter 2 numbers: " output, so when you call that function after your main() gives the output "Sum is: ", it is clear that the complete output is "Sum is: Enter 2 numbers: ".
You need to rewrite your code (especially the function sum()) to get the output in the order you want it to be.
Example:
#include<iostream>
using namespace std;
int sum();
int main() {
sum();
return 0;
}
int sum() {
int num1,num2;
cout << "Enter 2 numbers: " << endl;
cin >> num1 >> num2;
cout << "Your sum is: " << (num1+num2) << endl;
return 0;
}

You're not getting "Enter 2 numbers" first because in the main function this line is called first.
cout << "Sum is: " << sum() << endl;
which is equivalent to
cout << "Sum is:";
cout << sum();
cout << endl;
The first line prints
Sum is:
To the standard output and then it calls the function sum()
which prints Enter 2 numbers:
So the standard output is:
Sum is:
Enter 2 numbers:
Then the function returns and you get the result and the newline.
To change this either take the input in the main function or just take the return value of the function in a variable;
#include<iostream>
using namespace std;
int sum();
int main() {
int s = sum;
cout << "Your sum is: " << s << endl;
return 0;
}
int sum() {
int num1,num2;
cout << "Enter 2 numbers: " << endl;
cin >> num1 >> num2;
return (num1 + num2);
}

Related

Check special character in string array using isalpha

So I am trying to take words from a file and save them into a dynamic array, and then print the array sorted alphabetically along with the concordance of each word in the array. I am facing a problem in identifying special characters/ numbers and deleting them from the array. I want to use the isalpha function as it is in the assignment prompt. When I run my code, it works perfectly but special characters and numbers are not eliminated from the array. Any idea on how to do this using isalpha?
#include <iostream>
#include <stream>
#include <iomanip>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <string>
using namespace std;
void loadData();
void checkSpecialCharacters(string wordPtr, int size);
void alphabeticalSort(string *wordPtr, int size);
void frequencyCounter(string *wordptr, int size);
int main()
{
loadData();
return 0;
}
void loadData()
{
string fileName;
cout << "This program processes any text file to give you the concordance for each word present, and how many times it appears in the file." << endl;
cout << "Please enter the name of the text file you want to process followed by '.txt': " << endl;
cin >> fileName;
ifstream dataFile(fileName);
if (dataFile.fail())
{
cerr << fileName << " could not be opened." << endl; //error message if file opening fails
exit(-1);
}
string word;
int size = 0;
while (dataFile >> word)
{
size++;
}
dataFile.clear();
dataFile.seekg(0);
string* wordPtr = new string[size];
int ctr = 0;
for (int i = 0; i < size; i++)
{
dataFile >> wordPtr[i];
checkSpecialCharacters(wordPtr[i], size);
std::transform(wordPtr[i].begin(), wordPtr[i].end(), wordPtr[i].begin(), ::tolower);
cout << wordPtr[i] << endl;
}
dataFile.close();
alphabeticalSort(wordPtr, size);
frequencyCounter(wordPtr, size);
delete[] wordPtr;
}
void checkSpecialCharacters(string wordPtr, int size)
{
for (int i = 0; i < size; i++)
{
if (isalpha(wordPtr[i]) == true)
{
for (int j = 0; j < size; j++)
{
wordPtr[j] = wordPtr[j + 1];
cout << wordPtr[j];
}
}
}
}
void alphabeticalSort(string *wordPtr, int size)
{
int i, j;
string temp; //temporary holding variable
for (i = 0; i < (size - 1); i++)
{
for (j = 0; j < (size - 1); j++)
{
if ((wordPtr[j])>(wordPtr[j + 1]))
{
temp = wordPtr[j];
wordPtr[j] = wordPtr[j + 1];
wordPtr[j + 1] = temp;
}
}
}
}
void frequencyCounter(string *wordPtr, int size)
{
string finalFileName;
cout << "Please enter the name of the file that you want to store the concordance in followed by .txt: " << endl;
cin >> finalFileName;
ofstream concordanceFile(finalFileName, ios::out);
if (concordanceFile.fail())
{
cerr << finalFileName << " could not be opened." << endl;
exit(-1);
}
int frequency = 1;
int index = 1;
string element = wordPtr[0];
while (index < size)
{
if (wordPtr[index - 1] == wordPtr[index]) // check if element is equal to previous element
{
frequency++;
index++;
}
else
{
concordanceFile.setf(ios::left);
concordanceFile << setw(10) << element << " " << setw(10) << frequency << endl;
cout.setf(ios::left);
cout << setw(10) << element << " " << setw(10) << frequency << endl;
element = wordPtr[index];
index++;
frequency = 1; //reset frequency
}
}
cout << "Concordance data saved in " << finalFileName << " successfully!" << endl;
}

std::for_each and std::vector destructor call

I have the following problem with std::for_each and a functor proxy object.
See the following code:
struct Functor {
std::vector<int> data;
const unsigned mID;
static unsigned id;
Functor() : mID(id++) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}
~Functor() {
std::cout << "Functor dtor: " << mID << std::endl;
}
void operator() (int i) {
std::cout << "Functor print: " << i << std::endl;
data.push_back(i);
std::cout << "Dump: ";
for(int i = 0; i < data.size(); ++i)
std::cout << data[i] << " ";
std::cout << std::endl;
}
};
unsigned Functor::id = 0;
From above, the proxy object simply does 2 things, it prints the data out to the CMD and it stores a copy for itself to use. Below is the example use case of the object:
int main () {
std::vector<int> intvec;
for(int i = 0; i < 10; ++i)
intvec.push_back(i);
Functor myfunctor;
std::for_each(intvec.begin(), intvec.end(), myfunctor);
std::cout << "Data in my functor: " << myfunctor.data.size() << std::endl;
for(int i = 0; i < myfunctor.data.size(); ++i)
std::cout << "myfunctor data: " << myfunctor.data[i] << std::endl;
return 0;
}
This is the part it gets really fishy for me. The output generated is that my functor proxy object is constructed once but deconstructed three times! Something is bypassing the construction call.
Also as a result of the destructor being called at the end of the std::for_each, the Functor.data is empty as well!
Is there a way to make sure data inside Functor is kept persistent? I wish to keep track of the state of my functor when used inside functions such as std::for_each (Basically any given std algorithm function that can take in a unary functor)
Do note that I am using c++03 ONLY. Many thanks.
[...] my functor proxy object is constructed once but deconstructed three times! Something is bypassing the construction call.
Not quite. Your class is default-constructed once, but is also copy-constructed twice. You don't log the copy construction, so it doesn't show up on your output.
If you add a logging copy constructor, you'll see "Functor constructed with id: 0" printed three times:
Functor(const Functor& other) : mID(other.mID) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}

introduce c++ into html

So I need to create a data base of a student and his marks in class. I did it by using massive Arrays of objects, but I need to write it in html file like a table, and I create special function save.
#include <iostream>
#include "windows.h"
#include <fstream>
#include "TkachenkoLab.h"
using namespace std;
void save(Student KI[]);
ofstream file_out("C:\\Users\\ТКаченко\\Desktop\\МП ЛАБ №7\\LAB7\\page.html");
int main()
{
SetConsoleCP(::GetACP());
SetConsoleOutputCP(::GetACP());
short n;
cout << "Ââåä³òü ê³ëüê³ñòü ñòóäåíò³â ãðóïè: ";
cin >> n;
cin.clear(); cin.sync();
cout << "\n —-— ÑÒÂÎÐÅÍÍß ÃÐÓÏÈ Ê² —---\n";
Student KI[n];
cout << "\n —-— ÑÏÈÑÎÊ ÃÐÓÏÈ Ê² —---\n";
short i;
for (i = 0; i < Student::cnt(); i++ )
cout << i+1 << ". " << KI[i].name << endl;
cout << "\n —-— reading student —-— \n";
for (i = 0; i < Student::cnt(); i++ )
KI[i].in_res();
save(KI);
if (file_out.is_open())
file_out.close();
return 0;
}
void save(Student KI[])
{
file_out.open("C:\\Users\\ТКаченко\\Desktop\\МП ЛАБ №7\\LAB7\\page.html",ios::trunc);
file_out << "<html>" << endl;
file_out << "<head>" << endl;
file_out << "</head>" << endl;
file_out << "<body>" << endl;
file_out << "<table class=\"simple-little-table\">" << endl;
file_out << "<tr>" << endl;
file_out << "<td>студент</td>" << endl;
file_out << "<td>мп</td>" << endl;
file_out << "<td>кс</td>" << endl;
file_out << "<td>физра</td>" << endl;
file_out << "<td>средний бал</td>" << endl;
file_out << "</tr>" << endl;
for (short i = 0; i < Student::cnt(); i++ )
{
file_out << "<td>студент</td>" << endl;
file_out << "<td>"<<KI[i].name<<"</td>" << endl;
file_out << "<td>"<<KI[i].MP<<"</td>" << endl;
file_out << "<td>"<<KI[i].KC<<"</td>" << endl;
file_out << "<td>"<<KI[i].fiz_ra<<"</td>" << endl;
file_out << "</tr>" << endl;
}
file_out << "</table>" << endl;
file_out << "</body>" << endl;
file_out << "</html>" << endl;
file_out.close();
}
my class in library
#include <string>
using namespace std;
class Student
{
public:
Student();
static short cnt() { return cnt_stud; };
void in_res();
void out_res();
string name;
~Student() {};
short MP, KC, fiz_ra;
static short cnt_stud;
short s_bal () { return (short)(MP+KC+fiz_ra)/3; };
};
void Student::out_res()
{
}
Student::Student()
{
cout << "ПІБ студента: ";
getline(cin, name);
MP = 0;
KC = 0;
fiz_ra = 0;
cnt_stud++;
};
short Student::cnt_stud = 0;
void Student::in_res()
{
cout << name << ": ";
cin >> MP; cin >> KC; cin >> fiz_ra;
}
It is didn't even create a file. What did I do wrong?
First you're using non-ascii characters in your pathname. I've never tried to do it so I can't help you there but maybe you can try the answer here Open File with Non ASCII Characters
You're doing it wrong, the way you go about writing to the file. I assume that you're trying to write all students into the same file, but don't make your file a global variable, pass it to the function like this.
void save( std::ofstream &file, Student KI[] );
And check things in main like this,
int main() {
std::ofstream file( "PathOfFile" );
if ( file.is_open() ) {
// Do what you want to do with your file
save( file, student );
file.close();
}
else {
std::cout << "Failed to open file" << std::endl;
}
return 0;
}
It's easier for us to read and for you to work with.

Getting ifstream from istream and calling functions via overloaded >> operator

I've created an object, PDBParser, to extract information from a PDB file. Now I am trying to overload the >> and << operators so that I can use them from the main as so:
inFile >> MyPDBParser;
outfile << MyPDBParser;
I've got the << operator all set, but I can't seem to get the >> operator to work properly.
Here is the .h file for the PDBParser class to give you a better idea of what's going on:
#include <iostream>
#include <cstdlib>
#include "FloatArray.h"
#include "IntArray.h"
#include "Atom.h"
#include "AtomArray.h"
using namespace std;
class PDBParser
{
friend ostream& operator<<(ostream& _ostream, PDBParser &rhs);
friend istream& operator>>(istream& _istream, PDBParser &rhs);
public:
PDBParser();
PDBParser(string atom1, string atom2, int separation);
PDBParser(const PDBParser& orig);
virtual ~PDBParser();
void grabAtoms(ifstream &infile);
void findAtoms();
void setAtom1(string rhs);
void setAtom2(string rhs);
void setSeparation(int rhs);
string getAtom1();
string getAtom2();
int getSeparation();
private:
string atom1s;
string atom2s;
int separation;
AtomArray *atoms1;
AtomArray *atoms2;
AtomArray *matches1;
AtomArray *matches2;
FloatArray *x1;
FloatArray *y1;
FloatArray *z1;
FloatArray *x2;
FloatArray *y2;
FloatArray *z2;
IntArray *allsequence;
ifstream backupinfile;
void trim(string &rhs);
void incrementArrays(int newElements);
};
Essentially what I need the >> operator to do is get the infile from the istream and then call the grabAtoms(infile) and findAtoms() functions for this instance of the PDBParser object.
Here's what I have now, which doesn't work. Please forgive the commented lines, as they were things I was attempting to make work. I tried adding the backupinfile object to the PDBParser class just to make things work, so normally it didn't have this and doesn't use it.
istream & operator>>(istream & _istream, PDBParser &rhs)
{
// ifstream in;
// _istream >> rhs.grabAtoms(in) >> rhs.findAtoms();
_istream >> rhs.backupinfile;
rhs.grabAtoms(rhs.backupinfile);
rhs.findAtoms();
return _istream;
}
I've established that the issue here is that my function needs to receive an ifstream object and I can't figure out how to get that from the istream object.
Here's my working << overload just for the heck of it:
ostream & operator<<(ostream & _ostream, PDBParser &rhs)
{
for(int i=0; i < rhs.x1->getSize(); i++)
{
_ostream.precision(3);
_ostream << fixed;
_ostream << setprecision (3) << rhs.x1->get(i) << " ";
_ostream << setprecision (3) << rhs.y1->get(i) << " ";
_ostream << setprecision (3) << rhs.z1->get(i) << " ";
_ostream << setprecision (3) << rhs.x2->get(i) << " ";
_ostream << setprecision (3) << rhs.y2->get(i) << " ";
_ostream << setprecision (3) << rhs.z2->get(i) << endl;
}
return _ostream;
}
Thanks

Best way to separate parallel MPI part in sequential program

I've have a huge sequntial program, in which I want to parallelize some algo with MPI and CUDA. How correctly separate sequential part from parallel? The problem lies in nesting of parallel algo, and using of slurm or loadLeveler as well(e.g. on my MPI cluster I can't write something like: mpirun -n 1 a.out: -n 2 b.out).
Example:
int main()
{
funcA();
}
void funcA()
{
funcB();
}
void funcB()
{
parallel algo starts here....
}
I've found a great solution, for this problem. This is sample code:
#include <iostream>
#include <mpi.h>
#include <unistd.h>
using namespace std;
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int r;
MPI_Comm_rank(MPI_COMM_WORLD, &r);
if (r == 0) {
cout << "[GUI]Start perfoming initialization...." << endl;
sleep(2);
cout << "[GUI]Send command to start execution...." << endl;
int command = 1;
//TODO: now it's hardcoded to send data to 1 proc
MPI_Send(&command, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
cout << "[GUI]Waiting for execution results..." << endl;
int buf[5];
MPI_Recv(&buf, 5, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
for (int i=0; i<5; i++)
{
cout << "buf["<< i << "] = " << buf[i] << endl;
}
} else {
int command;
MPI_Recv(&command, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
cout << "Received command: " << command << endl;
if (command == 1) {
cout << "[ALGO]Receive command to start execution" << endl;
sleep(2);
cout << "[ALGO]Send computed data..." << endl;
int buf[5] = {5,4,3,2,1};
MPI_Send(&buf, 5, MPI_INT, 0, 0, MPI_COMM_WORLD);
}
}
MPI_Finalize();
return 0;
}