且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我该如何在C语言中正确地'printf'一个整数和一个字符串?

更新时间:2023-11-11 08:18:04

您处在正确的轨道上.这是一个更正的版本:

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

让我们来谈谈这些变化:

Let's talk through the changes:

  1. 分配一个整数(n)将您的电话号码存储在
  2. 告诉scanf首先读取一个字符串,然后读取一个数字(%d表示数字,正如您已经从printf
  3. 知道的那样
  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

这几乎就是它的全部.您的代码仍然有些危险,因为任何超过9个字符的用户输入都会溢出str并开始踩踏您的堆栈.

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.