---
title: "我的嵌入式学习笔记（2）--scanf使用常见问题及解决方法"
author: "cjc"
date: "2009-06-02T16:30:00Z"
tags: []
slug: "2-scanf"
draft: false
lastmod: "2009-06-02T16:30:00Z"
id: 402526
url: "https://cjc.iteye.com/blog/402526"
---

&lt;script&gt;function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}&lt;/script&gt;

**作者：**曹忠明，[华清远见嵌入式学院](http://www.embedu.org/)讲师。

在学习C语言的时候，printf（）是我们学到的第一个函数，相信“hello world”这个例子大家都不会陌生吧，接着就是scanf（）这个函数了，这个函数的功能是格式输入，它的函数原型是：

int scanf（const char \*format，…）；

这个函数的基本用法这里就不说了，这里介绍一些这个函数使用中常见的问题及解决方法：

第一，连续输入两个或多个字符的时候，第二次输入直接跳过了如：

int main（）  
{  
char a，b；  
scanf（“%c”，&a）；  
scanf（“%c”，&b）；  
return 0；  
}

输入 a回车 然后就退出了。

这个问题有很多说法有说是缓冲区没有清除，有说stdin这个流的问题，这里我们不去追究，这里介绍几个解决这种问题的方法：

int main（）  
{  
char a，b；  
scanf（“\\n%c”，&a）；  
scanf（“\\n%c”，&b）；或 scanf（“ %c”，&b）；%c前有空格  
return 0；  
}

这次再编译一下就没有问题了。

第二，使用scanf（）函数输入一句话的时候，如：

int main（）  
{  
char string\[50] ；  
scanf（“%s”，string）；  
printf（“%s\\n”，string）；  
return 0；  
}

输入：hello world！

结果：hello

显然这个结果没有达到我们的要求。

解决方法：

int main（）  
{  
char string\[50] ；  
scanf（“%\[^\\n]”，string）；  
printf（“%s\\n”，string）；  
return 0；  
}

重新编译一下，没有问题了吧！

这里如果要是连续输入多个语句的话也会出现连续输入字符的那种问题，当然解决方法也相同了。

这里是最常见的几个问题，可能还有其他的解决方法，希望和大家相互交流，能力有限有问题希望大家多多指教。