简体   繁体   English

如何在C中使用char数组创建字符串?

[英]How to create a string with a char array in C?

I am an Android and Java developer and I am not much familiar with C language. 我是一名Android和Java开发人员,对C语言不太熟悉。 As well as you know there is not a String type in C. All I want is getting chars, putting them into an char array and writing these characters as a string. 就像您所知道的那样,C语言中没有String类型。我想要的只是获取char,将它们放入char数组并将这些字符写为字符串。 How can I take the whole string which is a array of characters and put it into a variable? 如何将整个字符串(一个字符数组)放入一个变量中? This is my code but it does not work properly. 这是我的代码,但无法正常工作。 The log which I get is: 我得到的日志是:

I/        ( 2234): *********PROPERTY = 180000€¾Ü    €¾Ü €¾ 

It should have been 180000. 应该是180000。

int c;
char output[1000];
int count = 0;
char *property;
FILE *file;
file = fopen("/cache/lifetime.txt", "r");
LOGI("****************FILE OPEN*************");
if (file) {
    LOGI("*****************FILE OPENED************");
    while ((c = getc(file)) != EOF) {
        putchar(c);
        output[count] = c;
        ++count;
        LOGI("******C = %c", c);
    }
    property = output;
    LOGI("*********PROPERTY = %s", property);
    fclose(file);
}

What you are missing is a '\\0' . 您缺少的是'\\0' All strings in C are just a sequence of characters ending with a '\\0' . C中的所有字符串只是一个以'\\0'结尾的字符序列。

So, once your loop 所以,一旦你循环

while ((c = getc(file)) != EOF)

is done, you can add the statement 完成后,您可以添加语句

output[count] = '\0'

Below modifications are needed if you intend to return the property variable outside the local function and if output is a variable local to the function. 如果您打算将property变量返回到局部函数之外,并且output是函数局部变量,则需要进行以下修改。

In the above below line will need modification 在上面的下面一行将需要修改

property = output; 

You should allocate memory for property using malloc and then use strcpy to copy the string in output to property or do a strdup as suggested by Joachim in the comment. 您应该使用malloc为属性分配内存,然后使用strcpy将输出中的字符串复制到属性中,或者按照Joachim在评论中的建议执行strdup

Using strdup, the statement will be like below 使用strdup,该语句将如下所示

property = strdup(output); 

Determine whether the number of characters is known at compile time or runtime, then allocate the array either statically or dynamically: 确定在编译时或运行时是否知道字符数,然后以静态或动态方式分配数组:

char some_property [N+1]; // statically allocate room for N characters + 1 null termination

// or alternatively, dynamic memory allocation:
char* property = malloc (count + 1);

Then copy the data into the new variable: 然后将数据复制到新变量中:

memcpy(some_string, output, count); 

some_string[count] = '\0'; // null terminate

...
free(property); // clean up, if you used dynamic memory (and only then)

Or simply use the "output" variable already in place, by adding a null termination at the end of the input. 或通过在输入的末尾添加一个空终止符来简单地使用已经存在的“输出”变量。

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

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