【问题标题】:C programming printf [closed]C 编程 printf [关闭]
【发布时间】:2023-03-04 16:11:01
【问题描述】:

我必须打印两个不同的字符串,但它崩溃了! 所以,我认为我只是在编程方面失败了,但我是新手,我不知道是什么!代码如下:

#include <stdio.h>
#include <conio.h>

int main(void)
{
    char nome1,nome2;
    int num1,num2;
    printf("inserisci il nome del primo giocatore ");
    scanf("%s",&nome1);
    printf("inserisci il nome del secondo giocatore ");
    scanf("%s",&nome2);
    printf("i giocatori sono: %s,%s", nome1,nome2 );
    getch();
    return 0;
}

【问题讨论】:

  • 除非您的输入是空字符串,否则scanf()s 会表现出未定义的访问越界行为。
  • 尝试使用%c 而不是%s

标签: c printf


【解决方案1】:

您需要为已定义的变量分配一些存储空间nome1nome2

所以,不要这样说:

char nome1,nome2;

为这些变量分配一些内存

char nome1[100],nome2[100];

此外,为防止缓冲区溢出,请使用fgets 而不是scanf

fgets(nome1, 100, stdin);

所以,你的代码是这样的:

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

int main(void)
{
    char nome1[100],nome2[100];
    int num1,num2;
    printf("inserisci il nome del primo giocatore ");
    fgets(nome1, 100, stdin);
    printf("inserisci il nome del secondo giocatore ");
    fgets(nome2, 100, stdin);
    strtok(nome1, "\n");    //removing the newline.
    printf("i giocatori sono: %s,%s", nome1,nome2 );
    getch();
    return 0;
}

【讨论】:

  • 别忘了删除换行符。
  • @Barmar,添加 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 2011-06-30
  • 2011-02-25
  • 2015-12-09
相关资源
最近更新 更多