c - 如何在c中将字符串存储在数组中?
问题描述
我尝试使用 strlen 来计算字符并将变量命名为 n 并创建了一个名称为 [n+1] 的数组,但变量 n 不是全局变量,所以我遇到了一些问题,因为计算机不理解 n是。为了计算 n 我创建了另一个函数
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
int count_characters(string text);
int n;
int main(void)
charcters [n+1]
{
string t = get_string("text: ");
printf("letter(s)");
}
int count_characters(string text)
{
n = strlen(text);
return n;
}
解决方案
您对 in 的值的使用n
必须在分配给 之后n
。
你想要的可能是:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
int count_characters(string text);
int n;
int main(void)
{
string t = get_string("text: ");
printf("letter(s)");
/* call the function to have it assign to n */
count_characters(t);
/* now the length is assigned to n, so use it */
/* also don't forget the type name for elements */
char charcters [n+1];
/* store a string */
strcpy(charcters, t);
}
int count_characters(string text)
{
n = strlen(text);
return n;
}
推荐阅读
- sql - 列出不同的案例重复 SQL Server
- github - 为什么 JENKINS 忽略 environment.yml (conda) 中所需的包?
- java - SSL 握手以 javax.net.ssl.SSLException 结尾:readHandshakeRecord
- functional-programming - 函数式语言编译器是否将列表上的“过滤,然后映射”操作优化为单遍?
- powershell - 如何在powershell中打印将一个值作为输入的对象的内容?
- notifications - Colab 音频警报或弹出通知,提醒用户在弹出时点击验证码按钮,防止不活动
- r - 修改小标题列表中的小标题(其次是按尺寸大小过滤小标题列表)
- c# - 是否值得存储查询结果而不是使用 EF Core 从数据库中获取它们?
- javascript - JHipster 前端 JS 支持
- node.js - Firbase/Heroku/Node JS - Firebase 凭据无效/无法解析服务帐户 json 文件/ENAMETOOLONG