首页 > 解决方案 > 如何在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;
}

标签: carrayscs50

解决方案


您对 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;
}

推荐阅读