Question

I am trying to read songs into string variables in C. I use a dash ("-") to distinguish between the artist and the song. This is the program:

#include <stdio.h>

int main() {
    char *artist, *song;
    printf("Please copy all of the songs you wish to download below.\n");
    printf("When you have finished, please input a full stop.\n\n");
    scanf("%[^-] %s", artist, song);
    printf("%s %s\n", artist, song);
    return 0;
}

When I use this program, entering, for example, "artist - song", the output is as follows:

Please copy all of the songs you wish to download below.
When you have finished, please input a full stop.

artist - song
artist  (null)

I have tried using scanf("%[^-] %[^\n]", artist, song); and the result is the same.

How would I get everything after the dash to be read?

Était-ce utile?

La solution

artist and song are pointers. They do not point anywhere valid. You cannot use them before you make them point somewhere valid.

Try arrays instead.

#include <stdio.h>

int main(void) {
    char artist[100], song[100]; // arrays, not pointers
    printf("Please copy all of the songs you wish to download below.\n");
    printf("When you have finished, please input a full stop.\n\n");
    if (scanf("%99[^-]-%99s", artist, song) != 2) /* error */;
    printf("%s %s\n", artist, song);
    return 0;
}

Or, if you want to use pointers, allocate memory for them before input

#include <stdio.h> /* printf(), scanf() */
#include <stdlib.h> /* malloc(), free() */

int main(void) {
    char *artist, *song;
    artist = malloc(100);
    if (!artist) /* error */;
    song = malloc(100);
    if (!song) /* error */;
    printf("Please copy all of the songs you wish to download below.\n");
    printf("When you have finished, please input a full stop.\n\n");
    if (scanf("%99[^-]-%99s", artist, song) != 2) /* error */;
    printf("%s %s\n", artist, song);
    free(song);
    free(artist);
    return 0;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top