For C++: (Use only conditions, loops, user defined functions and arrays) Suppose you had data in a file (input.txt) like this
1 2 6 11 4 8 12 3 16 5 6 14 ………
Find the multiples of 2 in order and store it in the output file (output.txt) like this
2 4 ..........
The number 6 is in the wrong position so the order was disturbed. 6 only comes after 4. Therefore 6 and the other multiples of 2 were also skipped.
// Header Files
#include <iostream>
#include <fstream>
#include<conio.h>
#include<stdio.h>
//Standard namespace declaration
using namespace std;
//Main Function
void main () {
const int SIZE = 100;
std::ifstream fin("input.txt");
std::ofstream outfile("output.txt");
outfile.open();
if (fin.is_open())
{
std::string words[SIZE];
std::string str;
std::cout << "Read from a file!" << std::endl;
for (int i = 0; (fin >> str) && (i < SIZE); ++i) // Will read up to eof() and stop at every whitespace it hits
{
words[i] = str;
}
fin.close();
std::cout << std::endl;
int multiple=2;
for (int i = 1; i <=SIZE; ++i)
{
if( words[i] == multiple*i){
outfile << words[i];
multiple=multiple*i;
}
//std::cout << words[i] << std::endl;
}
}
else cout << "Unable to open file";
getch();
}
Get Answers For Free
Most questions answered within 1 hours.