In: Computer Science
#include <stdio.h>
#include <stdlib.h> // required for atoi
int main(void) {
int i=0,n,num,filenum[100],pos;
int c;
char line[100]; //declaring string for storing data in
the line of text
FILE *fp; // declaring a FILE pointer
fp=fopen("numbers.txt","r"); // open a text file for
reading
while(fgets(line, sizeof line, fp)!=NULL)
{ // looping until end of the
file
filenum[i]=atoi(line);
//converting data in the line to integer and storing it into
array
i++;
}
n=i;
fclose(fp); //closing file
printf("Enter a number: ");
scanf("%d",&num);
while(num!=EOF) //looping until user enters end of the
file
{
pos=0;
for(i=0;i<n;i++)
{
if(num==filenum[i]) //if num is equal to
filenum[i]
{
pos=i+1;
}
}
if(pos>0)
printf("%d last
appears in the file at position %d\n",num,pos);
else
printf("%d does
not appear in the file\n",num);
printf("Enter a number: ");
scanf("%d",&num);
}
return 0;
}
=====================================================
(does anyone can help me to change this program in C++ and add some comments)
numbers.txt: 10 23 43 5 12 23 9 8 10 1 16 9
you must to have all of following output:
Enter a number: 10
10 last appears in the file at position 9
Enter a number: 29
29 does not appear in the file
Enter a number: 9
9 last appears in the file at position 12
Enter a number:
Here is code:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int i = 0, n, num, filenum[100], pos;
int c;
char line[100]; //declaring string for storing data in the line of text
ifstream fin("numbers.txt");
int a;
while (fin >> a) // read the number untill EOF
{ // looping until end of the file
filenum[i] = a; //converting data in the line to integer and storing it into array
i++;
}
n = i;
fin.close();
cout << "Enter a number: ";
cin >> num;
while (num != EOF) //looping until user enters end of the file
{
pos = 0;
for (i = 0; i < n; i++)
{
if (num == filenum[i]) //if num is equal to filenum[i]
{
pos = i + 1;
}
}
if (pos > 0)
cout << num << " last appears in the file at position " << pos << "\n";
else
cout << num << " does not appear in the file\n";
cout << "Enter a number: ";
cin >> num;
}
return 0;
}
Output: