简体   繁体   English

如何将字符串存储在 c 中的数组中?

[英]how can i store a string in an array in c?

I tried using the strlen to count the characters and named the variable n and created an array with a name [n+1] but the variable n is not a global variable so I'm having some problems as the computer does not understand what n is.我尝试使用 strlen 来计算字符并将变量命名为 n 并创建了一个名称为 [n+1] 的数组,但变量 n 不是全局变量所以我遇到了一些问题,因为计算机不明白什么 n是。 To calculate n I created another function为了计算 n 我创建了另一个 function

#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;
}

Your usage of values in n must be after the assignment to n .您对n中的值的使用必须在对n赋值之后。

What you want may be:你想要的可能是:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM