首页 > 解决方案 > 左对齐的字符串在下一行打印出来并且不正确

问题描述

我目前正在尝试打印一个输入数组,只有一个二维数组的一部分被左对齐,而另一部分被发送到下一行,任何帮助都会很棒!问题出在我的 printSongInfo 函数上,但已包含其余代码以帮助理解。我正在寻找要显示为左对齐并显示在该行的前 35 个字符中的艺术家,以及要左对齐并显示在同一行的下一个 35 个字符中的歌曲,然后再转到下一行并重复该过程对于所有 10 个索引。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#pragma warning(disable:4996)

int getSongInfo(struct songInfo *pFillInfo, char *artistName, char *songName);
void printSongInfo(struct songInfo songList[10]);

struct songInfo {

    char *songArtist;
    char *songTitle;
};

int main(void)
{
    struct songInfo *fillPtr;
    struct songInfo songList[10];
    fillPtr = &songList[0];

    char tempArtist[30][10];
    char tempSong[30][10];

    int i = 0;
    int counter = 0;
    int arrayCounter = 0;
    while (counter != 10)
    {
        printf("Please enter the artist name: ");
        fgets(tempArtist[counter], sizeof(tempArtist[counter]), stdin);
        printf("Please enter the song name: ");
        fgets(tempSong[counter], sizeof(tempSong[counter]), stdin);

        getSongInfo(&fillPtr[arrayCounter], tempArtist[counter], tempSong[counter]);

        printf("Song and Artist Captured! \n");
        counter++;
        arrayCounter++;
    }

    printSongInfo(fillPtr);
}

int getSongInfo(struct songInfo *pFillInfo, char *artistName, char *songName)
{
    pFillInfo->songArtist = (char*)malloc(strlen(artistName) + 1);
    pFillInfo->songTitle = (char*)malloc(strlen(songName) + 1);

    strcpy(pFillInfo->songArtist, artistName);
    strcpy(pFillInfo->songTitle, songName);



    return 1;
}

void printSongInfo(struct songInfo songList[10])
{
    int counter = 0;


    while (counter != 10)
    {
        printf("%-35s %-35s\n", songList[counter].songArtist, songList[counter].songTitle);
        counter++;
    }

}

我正在寻找匹配相同且不被发送到下一行的号码。所以 1 & 1 应该在同一行上看到。

电流输出:

在此处输入图像描述

标签: carraysstringprintf

解决方案


推荐阅读