0

I have an assignment where I implement binary search and linear search. The "hard" part is done and both of the those methods are implemented and work. My professor wants us to test arrays with large number of integers. He gave us a .in file that had input in the style that he wants and I'm trying to use freopen to read the file.

int main(int argc, const char * argv[]) {

freopen("input.in", "r", stdin);  // <-----

int n , s;

scanf("%d %d", &n, &s);

int myAr[n];
int i = 0;
while (i < n) {
    scanf("%d",&myAr[i]);
    i++;
}

int myAr2[s];
int j = 0;
while (j < s) {
    scanf("%d",&myAr2[j]);
    j++;
}
...

The file starts out with 2 numbers in one line, number of elements in the list and the number of element that you are looking for in the first list.

then it read a line with all the numbers in list 1 and then the next line reads all the numbers in list 2

I can't get freopen() to work properly and I would like to know if there are any suggestions out there.

sample input.in file:

10 2
2 4 6 7 9 10 24 26 29 33
26 35

My code would later tell me that 26 is found and 35 was not. My main issue is reading the input file in main instead of manually typing in the terminal. Help please.

4

1 回答 1

1

我通过简单地使用来读取 input.in 文件中的所有整数fscanf()

这是我的代码。

int j;
FILE *fp;
fp = fopen("input.in", "r");
while( fscanf(fp,"%d",&j) > 0 )
{
    printf("%d\n", j);
}
fclose(fp);

输出是。

在此处输入图像描述

于 2015-03-17T08:06:59.717 回答