如何正确的printf在C整型和字符串? [英] How to properly printf integer and string in c?

查看:91
本文介绍了如何正确的printf在C整型和字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code:

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);

当我运行code,并输入输入A 1如下:

When I run the code, and enter the input "A 1" as follow:

type a string: A 1

我得到了以下结果:

I got the following result:

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:


  1. 分配一个int( N )来存储你的电话号码

  2. 告诉 scanf函数阅读第一字符串,然后一个数字(%d个指数,因为你已经从知道你的的printf

  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

这是pretty很多都在那里给它。您code是有点危险,不过,因为这是超过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.

这篇关于如何正确的printf在C整型和字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆