Search code examples
cscanfnewlinefgetsc-strings

How to read strings until end of input, with reading lines until \n is found in C?


I would like to read strings in while loop, until end of input, but I dont know how. For example, input is:

Car
Black car
White car

First, I want to scanf 'car' and save it in array. Then, I want to scanf 'Black car' and put it into aray, and so on.

 while (scanf("%[^\n]", s)>0)

This reads only one line, but when I use this code:

 while(scanf("%s", s) > 0)

It reads one word after another, so there will be no 'Black car', but 'black' and 'car'.

Do you have any idea to make this two conditions together?

And, I have got two nodes in linked list: first is 'White car' and second is 'Car black'. I want to sort it in alphabetical order. I want to get into array1 the first letter of 'White car', which is 'W' and into array 2 the first letter of 'Car black', which is 'C'. But when I printf array1, it print'W', but when I want to print array2, it writes 'CW'? When I printf one->name, it print 'White Car' and when I printf two->name, it print 'Car black'.

void sort(Car**head){
Car*one;
Car*two;
Car*temp;
one= *head;
two= one->next;

int compare;
char array1[1]={0};
char array2[1]={0};

while(one->next){
    compare= 0;
    strncpy(array1, one->name, 1);
    strncpy(array2, two->name, 1); 

    printf("Array1: %s\n", array1);
    printf("Array2: %s\n", array2);

    printf("One name: %s\n", one->name);
    printf("Two name: %s\n", two->name);

    compare= strcmp(one->name, two->name);
    if(compare<0){
        temp = one;
        one = two;
        two= temp;
    }
    one = one->next;
    two = two->next;
}                           

}


Solution

  • Use the standard C function fgets. For example

    char s[N];
    while ( fgets( s, sizeof( s ), stdin ) != NULL && s[0] != '\n' )
    {
        //...
    }
    

    Where N is some integral value.

    Here is a demonstrative program

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        enum { N = 100 };
        char s[N];
    
        while ( fgets( s, sizeof( s ), stdin ) != NULL && s[0] != '\n' )
        {
            s[ strcspn( s, "\n" ) ] = '\0';
            puts( s );
        }
    
        return 0;
    }
    

    if to enter

    Car
    Black car
    White car
    

    and after the last input press one more Enter then the output will be

    Car
    Black car
    White car
    

    This statement

    s[ strcspn( s, "\n" ) ] = '\0';
    

    is used to exclude the new line character '\n' from the entered string. This character can be appended to the entered string by the function fgets.