我正在使用 Visualstudio 2015 用 C 语言制作一个控制台应用程序,以便用户可以输入他们想要制作的糖果数量以及糖果的名称,但是有一个问题,问题是当程序尝试读取时数组中的字符串程序崩溃并且不打印任何内容,但是如果我将其更改为使用 %c 打印单个字符,它将打印出字符串的第一个字符,例如,如果我输入 2 个糖果和字符串“Jawbreaker”和 'Lollipop' 如果我使用 %s 作为字符串,它会崩溃,但是如果我使用 %c 作为字符,它会完成它的工作并分别在不同的行上打印 'J' 和 'L',有什么想法我可以得到这个使用字符串的 %s 说明符?
代码如下:
#include <stdio.h>
/*Declares the variable needed*/
int sweet_number;
char sweet_name[999];
int main(void) {
/*Prompts the user to enter the number of sweets and saves it to sweet_number*/
printf("Please enter the number of sweets:\n");
scanf("%d", &sweet_number);
/*for loop to enter the name of the sweet into the array*/
for (int i = 0; sweet_number > i; i++) {
printf("What is the name of the sweet?\n");
scanf("%s", &sweet_name[i]);
}
/*Prints array to screen*/
for (int j = 0; sweet_number > j; j++){ /* <- This is where code fails to run*/
printf("%s\n", sweet_name[j]);
}
return 0;
}
最佳答案
您必须使用二维数组。 sweet_name
是一个一维数组,每个索引最多可以存储一个字符而不是字符串。更改以下行
char sweet_name[999];
到
char sweet_name[999][100];
关于C语言循环打印数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584326/