简体   繁体   中英

For a program that takes a single number from a user, how can you test several values at once and then output them to a text file?

I have written a fairly simple program in C that takes an input n and computes the n'th number in the fibonacci sequence. When this program runs, you enter a number on your keyboard, and it prints out the result. My question is, I can only manually test one input at a time, to check for bugs. How can I write a program to test several inputs at the same time, and output this to a readable text file?

I have tried writing a program to run these tests, but I don't know how to make the program use my function which is written in a separate file. I appear to be able to only test one at a time, and When I output the result to a text file, I cannot read the text file either, it is empty.

The easiest solution would be to migrate your code to a function then call it in a loop:

#include <stdio.h>

long fib(long n) {
   // ...
}

int main() {
    long n = 2;
    for(long i = 0; i < n; i++)
        printf("%ld %ld\n", i, fib(i));
}

In order to so you will have to separate i/o (prompting user for input) from the function that implements the Fibonacci algorithm. This is a good design practice in general. You can build two programs (one interactive and one not), or a single program and for instance drive that with a command line argument:

int main(int argv, char argv[]) {
    if(argc == 2) {
        long n = atol(argv[1]);
        for(long i = 0; i < n; i++)
            printf("%ld %ld\n", i, fib(i));
        return 0;
    }
    printf("n? ");
    long n;
    if(scanf("%ld", &n) != 1) return 1;
    printf("%ld %ld\n", n, fib(n));
}

I suggest you print the data then redirect the stdout to a file. You will have to show us some code to figure out why your text output file feature is not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM