gpt4 book ai didi

c - scanf() 中不同数量的元素

转载 作者:太空宇宙 更新时间:2023-11-04 06:00:42 25 4
gpt4 key购买 nike

我如何告诉我的程序如何改变 scanf 读取的元素数量?我想让它读取字符串中的每个字符,字符串的长度可能从一个字符到一百个字符不等。我知道我可以执行 scanf("%c%c%c%c...") 一百次,但是有更简单的方法吗?

最佳答案

当然,使用具有适当大小的缓冲区的 fgets():

char buf[LINE_MAX];
if (fgets(buf, sizeof buf, stdin) != NULL) {
// input is now in `buf'
}

如果你真的不会使用数组,那么调用getchar()直到它找到一个换行符:

int sum = 0;

int ch;
while ((ch = getchar()) != EOF && ch != '\n') {
sum += ch;
}

(这已经做了你想要的,即它对用户输入的字符串的字符代码求和。)

关于c - scanf() 中不同数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19806131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com