c - C- getchar() re-read characters?
问题描述
is there a way that I can read a character with getchar() and read the same character with another getchar()?
for example the user gives 5 and the first getchar() reads 5 and then the second getchar() re-reads the 5.
thanks in advance!
解决方案
是的,您可以使用ungetc()
将字符放回输入流中。
这是一个示例程序:
#include <stdio.h>
int main(void) {
printf("Type something: ");
int c = getchar();
printf("Ok, you typed '%c'. Putting it back...\n", c);
ungetc(c, stdin);
printf("Reading it again...\n");
c = getchar();
printf("Still '%c'. Putting it back again...\n", c);
ungetc(c, stdin);
printf("Reading it again...\n");
c = getchar();
printf("Still '%c'!\n", c);
}
运行它:
Type something: smackflaad
Ok, you typed 's'. Putting it back...
Reading it again...
Still 's'. Putting it back again...
Reading it again...
Still 's'!
推荐阅读
- django - Django 表单向导:跳过一步但仍提供数据
- python - 使用 np.ma.allequal() 时结果不正确
- scala - 如何将 JAR 文件上传到服务器
- node.js - 如何为一次性支付和免费重新注册实施 Stripe 支付系统
- git - 当我从功能分支执行“git pull origin master --rebase”时,我收到过时的传入代码
- python - 拟合 svm 模型 errorValueError: could not convert string to float: '[array([0.30067509, 0.11679184, 0.01250501, 等等
- php - mySQL - PHP:如何使用变量准备查询
- list - Flutter 将 Map 转换为 JSON 的 List
- r - R:str_replace 不替换字符串中的字符,包括特殊字符(+)?
- arrays - *ngIf 检查数组中的值