0

Say if I wanted to scan in the following input:

123456
567234
145689

in java I would do this

String x,y,z;
x=scanner.nextline();
y=scanner.nextline();
z=scanner.nextline();

and then x would have the first line of input, y would have the second, and z would have the third.

my question is how do something like this in C?

dshawn
  • 327
  • 1
  • 12

2 Answers2

0

"%d" indicates the input value will be digit.

int a,b,c;
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
Muhammed Ozdogan
  • 5,341
  • 8
  • 32
  • 53
0

As was mentioned in a comment, you should probably use the POSIX getline() function. This is a moderate approximation to what you're after:

#define _GNU_SOURCE /* Necessary on an embarrassingly old version of RHEL */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    // String x,y,z;
    //x=scanner.nextline();
    //y=scanner.nextline();
    //z=scanner.nextline();

    size_t x_sz = 0, y_sz = 0, z_sz = 0;
    char *x = 0, *y = 0, *z = 0;
    int x_len = getline(&x, &x_sz, stdin);
    int y_len = getline(&y, &y_sz, stdin);
    int z_len = getline(&z, &z_sz, stdin);

    printf("x: size = %zu, len = %d, data = [%s]\n", x_sz, x_len, x);
    printf("y: size = %zu, len = %d, data = [%s]\n", y_sz, y_len, y);
    printf("z: size = %zu, len = %d, data = [%s]\n", z_sz, z_len, z);

    free(x);
    free(y);
    free(z);
    return 0;
}

When run on its own source, it yields:

x: size = 120, len = 77, data = [#define _GNU_SOURCE /* Necessary on an embarrassingly old version of RHEL */
]
y: size = 120, len = 19, data = [#include <stdio.h>
]
z: size = 120, len = 20, data = [#include <stdlib.h>
]

That emphasizes that the newline is included in the string that's read by getline(). You probably won't need the #define on a modern system, though it does depend a bit on which compiler you're using too. GCC 5.x and above default to C11 (GNU-extensions to C11, aka -std=gnu11). That wasn't sufficient on this machine, but this machine is known to be running an old version of RHEL, and the headers state that getline() is not a part of POSIX, which hasn't been true since POSIX 2008 (that is, getline() is a part of POSIX 2008).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278