gpt4 book ai didi

c - 在 C 中使用 scanf 读取直到破折号

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:34 27 4
gpt4 key购买 nike

我正在尝试将歌曲读入 C 中的字符串变量。我使用破折号(“-”)来区分艺术家和歌曲。这是程序:

#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;
}

当我使用这个程序时,例如输入“艺术家-歌曲”,输出如下:

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

artist - song
artist (null)

我试过使用 scanf("%[^-] %[^\n]", artist, song); 结果是一样的。

我怎样才能读取破折号后的所有内容?

最佳答案

artistsong 是指针。他们没有指向任何有效的地方。在将它们指向有效位置之前,您不能使用它们。

尝试使用数组。

#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;
}

或者,如果你想使用指针,在输入之前为它们分配内存

#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;
}

关于c - 在 C 中使用 scanf 读取直到破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23268630/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com