【问题标题】:Why is the code displaying blank rather than strings in C?为什么代码显示空白而不是 C 中的字符串?
【发布时间】:2021-04-20 04:29:57
【问题描述】:

我希望代码显示来自用户输入的字符串,但代码显示为空白。有时,它还会显示空值和整数,而不是字符串。

这里是sn-p的代码:

typedef struct list{
    char DATA[30];
    int last;
} LIST;

LIST L;

int main(){
    char x

    printf("Enter name:");scanf(" %s",&x);insert(x);

    display();getch();
}

void insert (char x){
    L.last++;
    L.DATA[L.last] = x;
}

void display(){
system("cls");
printf("The list contains:\n");
    for (int i=0;i<=L.last;i++){
    printf("%d. %s\n",i+1,L.DATA[i]);
    }
}

请帮助我理解我做错了什么。任何帮助将不胜感激。

【问题讨论】:

  • scanf("%s",&amp;x) hmm... %s 用于扫描字符串,但 x 是蚂蚁整数。使用%d 扫描整数。
  • 确保使用 %s 来显示字符串而不是 %d 编辑:sniped
  • printf("%d.) %d\n",i+1,L[MAX].DATA[i]); 再次:%d 用于整数,%s 用于字符串。你可能想要printf("%d.) %s\n",i+1,L[i+1].DATA);(或者只是i而不是i+1
  • 另请注意:L[MAX] 超出范围访问,即在数组之外。
  • 您的问题没有正确的minimal reproducible example。它不包含任何必需的东西:输入;预期或实际产出;或解释问题中的整个代码片段应该做什么。

标签: c string char integer


【解决方案1】:

C 没有字符串类型,只有字符类型。当您声明 char x 来保存您的字符串时,那是单个字符而不是整个字符串。我已将其替换为 char x[100] - 它声明了一个包含 100 个字符的数组来保存字符串。如果这还不够长,你可以增加它。然后我将insert()LIST 更改为采用char*(指向字符数组的指针)而不是单个char

您的列表遇到了insert() 函数未写入第一个列表元素的问题。我通过在增加L.last 之前写入列表来解决这个问题。我还通过在 for 循环中将 &lt;= 更改为 &lt; 解决了 display 函数打印不存在的列表元素的问题。

typedef struct LIST
{
    char* DATA[30];
    int last;
} LIST;

LIST L;

void insert (char* x);
void display();

int main(){
    char x[100]; // Declare a character array to hold our string.
    printf("Enter name: ");
    scanf("%s", x); // Read the string into the array.
    insert(x); // Pass the memory address of the array to insert().
    display();
    getch();
}

void insert (char *x)
{
    L.DATA[L.last] = x; // Put the memory address of the array into the list.
    L.last++; // Increment the list counter.
}

void display()
{
    printf("The list contains:\n");
    for (int i=0; i < L.last; i++)
    { // Loop over the list, printing
        printf("%d. %s\n", i+1, L.DATA[i]);
    }
}

注意:由于数组只有 100 个字符长,如果用户输入超过 99 个字符,将导致缓冲区溢出并中断程序。此外,如果数组中声明的函数退出,则数组会自动解除分配(如果它在 main() 中声明,就像这里一样,这很好)。如果这是一个问题,您应该考虑使用getline(),它可以自动分配适当大小的字符串,而不是scanf()

【讨论】:

  • 我尝试了代码,但是条目会用当前的条目覆盖以前的条目。所以我得到如下结果: 1. Ron 2. Ron 3. Ron 4. Ron 代码应该这样做: 1. Ron 2. Ram 3. Joy 4. Kath
  • 您应该尝试使用malloc() 而不是char x[100] 来分配您的字符数组。这样,当函数退出时它不会被释放。我认为这是你的问题。您也可以使用我之前提到的getline()
猜你喜欢
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
  • 1970-01-01
  • 2020-03-15
相关资源
最近更新 更多