как я могу сохранить строку в массиве в c? - PullRequest
0 голосов
/ 19 июня 2020

Я попытался использовать strlen для подсчета символов и назвал переменную n и создал массив с именем [n + 1], но переменная 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;
}

1 Ответ

1 голос
/ 19 июня 2020

Значения в 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;
}
...