user2063321
user2063321

Reputation:

How to get line from string?

I'm trying to get read line by line from a string (char *). I tried to implement it from what I read online, but it's not working. I wrote this test code to get it working outside my project code, and it's still not working (seg faults on the first readline call).

Thanks in advance for any help!

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

static void parse_message(char *message);
static void readline(char *message, char *line, int *counter);

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

    printf("starting\n");


    char *message1 = "Chat {\nHey what's up do you like zebras?\n}\n";

    parse_message(message1);

    printf("Finished\n");
    return EXIT_SUCCESS;
}


static void parse_message(char *message){
    char *line = (char *) malloc (50 * sizeof(char));
    int *counter = 0;

    readline(message, line, counter);//read in first line

    if(strcmp(line, "CHAT {") == 0){
        readline(message, line, counter); //read in message
        printf("%s",message); //print message
        readline(message,line,counter); //read in close bracket
    } else{

        printf("Error occurred\n");
    }


}


static void readline(char *message, char *line, int *counter){

    int index = 0;
    while(message[*counter] != '\n'){
        line[index] = message[*counter];
        counter++;
        index ++;
    }   
}

Upvotes: 2

Views: 5446

Answers (1)

Eddie
Eddie

Reputation: 427

There are a few mistakes.

In parse_message, you should compare "message" to "CHAT {". Also, strcmp will not return 0 as the two strings are not identical. Use strncmp instead.

int *counter=0 mean a pointer of 0. You should just use "int" and pass the address of counter instead.

In readline(), You need to null terminate the string . *counter++ should be (*counter)++. Otherwise, you are incrementing the pointer but not the content of the pointer.

static void parse_message(char *message) {
    char *line = (char *) malloc (50 * sizeof(char));
    int counter = 0;
    char *startline = "Chat {";
    if(strncmp(message, startline, strlen(startline)) == 0){
        readline(message, line, &counter); //read in message
        printf("%s",message); //print message
        readline(message,line,&counter); //read in close bracket
    } else{
        printf("Error occurred\n");
    }
}


static void readline(char *message, char *line, int *counter){
    int index = 0;
    while(message[*counter] != '\n'){
        line[index] = message[*counter];
        (*counter)++;
        index ++;
    }
    line[index] = 0;
}

Upvotes: 1

Related Questions