开发者

how to make a BufferedReader in C

I am really new programming in C. How can I do the same in C, maybe in a more simple way than the one I do in Java?

Each line of the input has two integers: X and Y separated by a space.

12 1

12 3

23 4

9 3

InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(in);

int  n;
int k;

double sol;
String line = "";
line = buf.readLine();

while(开发者_Go百科 line != null && !line.equals("")){
    String data [] = line.split(" ");
    n = Integer.parseInt(data[0]);
    k = Integer.parseInt(data[1]);
    calculus (n,k);
    line = buf.readLine();
}


Use fgets() to read a line of text and sscanf() to parse it:

#include <stdio.h>

int main(void)
{
    int n, k;
    char line[64]; // adjust size as necessary

    while(fgets(line, sizeof line, stdin) && sscanf(line, "%d %d", &n, &k) == 2)
        printf("n=%d, k=%d\n", n, k); // dummy code

    return 0;
}

Using scanf() alone to read directly from stdin might be possible with scansets, but it's not as easy as it looks because whitespace characters (including newlines) are skipped.


No compiler, so please fix as needed. Also the variable decalrations are C++ style

#include <stdio.h>

...

while (!feof(stdin)) {
    int n = 0, k = 0;
    if (scanf("%d %d\n", &n, &k) != 2) continue;
    // do something with n and k
}

C++ solution (with streams) may be simpler still


fscanf(filehandle, "%d %d\n", n, k);


The file variable is called FILE

To open a file use fopen()

Reading and writing are done with fgets() and fputs()

This is all in stdio.h.

Example:

#include <stdio.h>

int main(){
    FILE *input = fopen("file.txt", "r");
    char text[100]; // Where we'll put our text we read
    fgets(text, 100, input); // Get up to 100 chars, stops at the first newline
    puts(text); // In your example, this should print out "12 1"
    fgets(text, 100, input); // Get the next up to 100 chars
    puts(text); // Prints "12 3"
    return 0;
}

Let me know if there's anything wrong with the code, I don't have a C compiler with me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜