簡體   English   中英

如何將字符串存儲在 c 中的數組中?

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

我嘗試使用 strlen 來計算字符並將變量命名為 n 並創建了一個名稱為 [n+1] 的數組,但變量 n 不是全局變量所以我遇到了一些問題,因為計算機不明白什么 n是。 為了計算 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;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM