PDA

View Full Version : C++ help....


hphan
09-28-2002, 07:29 PM
Các bạn biết làm sao đọc được an array of integers from files.txt không?
Trong file.txt này contain 2hàng 1cái là array of integers cái kia là 1element thôi, lấy cái element compare với cái array of integers coi có bao nhiêu số giống nhau...

for example:

file.txt contain
1 2 3 5 6 5 8 9 76 5 44 3
5

From the file.txt above the output on the screen should be: 3 (b/c 3 numbers of 5 are alike)...

Làm ơn gíup dùm đi cám ơn nhiều trước nhé.....
H....

CAptain DaLaZBoi
09-28-2002, 07:40 PM
a` ha

Try ur best then I will help u .....

To read from text... i think u need to use fstream.h

man... bay gio nghi~ la.i ... nhuc ca'i ddau

CAptain DaLaZBoi
09-28-2002, 07:44 PM
and something like

ifstream infile;
int count = 0;

infile.open("text.txt", ios::in);

while(infile)
if ( theElement == infile)
count++;

hphan
09-28-2002, 07:49 PM
Đại khái cái problem là như vầy, nhưng cái này không đúng vì nó không compare được.....coi lại dùm đi nhen...
À, cái này dùm recursive function instead of loop..
Cám ơn nhiều nhé....
(*_*)

#include <fstream.h>

#define Max 20
fstream inFile;

void My_occurrence(int array[], int &occurrence)
{
int i=0,elementX;
inFile >> array[i];
inFile >> elementX;
if(array[i]== elementX)
occurrence++;
My_occurrence(array,occurrence);

}
void main()
{
int array[Max],occurrence=0;
inFile.open("input.txt",ios::in|ios::nocreate);
if(inFile.fail()){
cout<<"Error opening files for input"<<endl;
return;
}
My_occurrence(array,occurrence);
cout<<"The occurrence: "<<occurrence<<endl;
inFile.close();
}

Trung Quốc
09-28-2002, 07:54 PM
or you can read everything from the first line and store in in an array. (Try to look for file or read file in your book. Do you know how to use dynamic array? If not then just make an array of 20 or something. Then write a loop to fill in 0 for every elements in the array.)

Then read the number from the second line then use the loop to check.

here is the pseudo code for the loop to check to see if any number is alike.

set counter=0

for i = 0 to maxarray
if thefirstarray[i] = numberofsecondline then
counter++
end if
end for loop

print counter

goodluck
QT

Trung Quốc
09-28-2002, 08:01 PM
oop, :)

Look like your program is going to run forever, no exit for the recursive. :) If it is up to me, I wouldn't use recursive for this program, however if your prof want it, then you should use it. Remember when you use a recursive, you should have a condition for your program to exit. :)

Look at my last post for more info.

QT