I'm at a loss as far as how to parse the line in getline(). I would like look at each char that is in the line.
So if someone were to type in: "Hello" into stdin, I'd like to be able to able to access the char array in this manner:
line[0] = 'H'
line[1] = 'e'
line[2] = 'l'
line[3] = 'l'
line[4] = 'o'
line[5] = '/0';
I've looked at getchar(), but I want to try and use getline() as I feel like it is more convenient. I've also looked at scanf(), but it skips whitespaces and doesn't let me parse the input as nicely as getchar() or getline().
Here is simple code that attempts at getting the first char of a line via stdin, but results in a seg fault:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int len;
int nbytes = 100;
char *line = (char *) malloc (nbytes + 1);
while(getline(&line, &nbytes, stdin) > 0){
printf("first char: %s", line[0]); //try and get the first char from input
/**
* other code that would traverse line, and look at other chars
*/
};
return 0;
}
Thanks.
Use the %c
format specifier to print out a single character.
The code
printf("first char: %s", line[0])
will try to treat line[0]
as the address of a char array. If you just want to print out the first character, change it to
printf("first char: %c", line[0])
// ^
There are a couple of other small changes you could consider in other parts of your code:
free(line)
after your while loop