我该如何在C语言中正确地'printf'一个整数和一个字符串? [英] How do I properly 'printf' an integer and a string in C?
问题描述
我有以下代码:
char *s1, *s2;
char str[10];
printf("Type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%s\n", s1);
printf("%s\n", s2);
运行代码时,按如下所示输入输入"A 1":
When I run the code, and enter the input "A 1" as follow:
Type a string: A 1
我得到以下结果:
A
�<�
我试图将第一个字符读取为字符串,将第三个字符读取为整数,然后将其打印在屏幕上.第一个字符始终有效,但是此后屏幕上只会显示随机内容....我该如何解决?
I'm trying to read the first character as a string and the third character as an integer, and then print those out on the screen. The first character always works, but the screen would just display random stuffs after that.... How should I fix it?
推荐答案
您处在正确的轨道上.这是一个更正的版本:
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:
- 分配一个整数(
n
)将您的电话号码存储在 - 告诉
scanf
首先读取一个字符串,然后读取一个数字(%d
表示数字,正如您已经从printf
知道的那样
- allocate an int (
n
) to store your number in - tell
scanf
to read in first a string and then a number (%d
means number, as you already knew from yourprintf
这几乎就是它的全部.您的代码仍然有些危险,因为任何超过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.
这篇关于我该如何在C语言中正确地'printf'一个整数和一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!