我试图打印包含两个字符串的结构数组。但是我的打印功能不会打印多个数组的两个索引。我不确定为什么,因为在我看来逻辑是正确的。
这是主要功能
// This is the googleapis.com 3rd party script. It has been downloaded
// by the browser, and is now in the process of being evaluated.
window.google = window.google || {}; // google is now defined
google.maps = google.maps || {}; // google.maps is now defined
// ==== Can my setTimeout fire here? =====
// My `if (typeof google === 'undefined')` would be
// FALSE here, even though this script has not finished loading!
// Or, due to the single thread, will the browser finish evaluating
// this script before allowing queued up setTimeouts to fire?
// =======================================
(function() {
// then a lot more
这是我打印库函数
const int MAX_LENGTH = 1024;
typedef struct song
{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
} Song;
void getStringFromUserInput(char s[], int maxStrLength);
void printMusicLibrary(Song library[], int librarySize);
void printMusicLibraryTitle(void);
void printMusicLibrary (Song library[], int librarySize);
void printMusicLibraryEmpty(void);
int main(void) {
// Announce the start of the program
printf("%s", "Personal Music Library.\n\n");
printf("%s", "Commands are I (insert), S (sort by artist),\n"
"P (print), Q (quit).\n");
char response;
char input[MAX_LENGTH + 1];
int index = 0;
do {
printf("\nCommand?: ");
getStringFromUserInput(input, MAX_LENGTH);
// Response is the first character entered by user.
// Convert to uppercase to simplify later comparisons.
response = toupper(input[0]);
const int MAX_LIBRARY_SIZE = 100;
Song Library[MAX_LIBRARY_SIZE];
if (response == 'I') {
printf("Song name: ");
getStringFromUserInput(Library[index].songName, MAX_LENGTH);
printf("Artist: ");
getStringFromUserInput(Library[index].artist, MAX_LENGTH);
index++;
}
else if (response == 'P') {
// Print the music library.
int firstIndex = 0;
if (Library[firstIndex].songName[firstIndex] == '\0') {
printMusicLibraryEmpty();
} else {
printMusicLibraryTitle();
printMusicLibrary(Library, MAX_LIBRARY_SIZE);
}
答案 0 :(得分:2)
我认为问题是由于在for循环外设置了empty = true
,然后检查(!empty)
,它将评估为false
。令我惊讶的是它是如何打印两个指数的。您应该设置empty = false
,因为您在函数调用之前已经检查了第一个索引。
答案 1 :(得分:1)
逻辑有两种终止列表的方法:1)如果达到条目数,或2)如果任何条目为空。
我预计第二个条件是在您预期之前停止列表。可能这个阵列没有像预期的那样构建(我没有看到那个部分),或者有些东西正在覆盖早期或中间入口。
答案 2 :(得分:1)
你的定义为:
typedef struct song
{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
}Song;
后来,你写了if (library[i].songName[i] != '\0')
这真的很奇怪:你为什么要用与lib相同的索引索引songname字符串?
所以我自然希望你的打印功能是:
// This function will print the music library
void printMusicLibrary (Song library[], int librarySize) {
for (int i = 0; i < librarySize; i ++) {
printf("%s\n%s\n\n", library[i].songName,
library[i].artist);
}
}
请注意,您可以通过测试library[i].songName[0] != '\0'
(注意0)跳过空歌名称,但我认为最好不要将它们添加到列表中(空歌名称是否为sens?)
(如果你决定解决这个问题,请注意你有另一个可疑的地方:if (Library[firstIndex].songName[firstIndex] == '\0')
具有相同的模式)