You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中为get_string的输入设置字符长度限制?

问题解决方案
  • 若你使用的是标准C语言,get_string并非标准库内置函数,可改用标准库的fgets实现字符串读取,示例代码:
#include <stdio.h>
#include <string.h>

int main() {
    char m[100]; // 定义足够容量的字符数组存储输入
    printf("Something: ");
    fgets(m, sizeof(m), stdin);
    // 移除fgets自动读取的换行符
    m[strcspn(m, "\n")] = '\0';
    return 0;
}
  • 若你在CS50学习环境中编写代码,需确保引入CS50头文件并在编译时链接对应库:
#include <cs50.h>
#include <stdio.h>

int main() {
    string m = get_string("Something: ");
    printf("You entered: %s\n", m);
    return 0;
}

编译命令需添加-lcs50参数,例如:gcc your_code.c -o your_program -lcs50

内容的提问来源于stack exchange,提问作者Alex S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 13:29:51