1 Star 0 Fork 1

Chobits/C Code

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
get_string.c 1.10 KB
Copy Edit Raw Blame History
Chobits authored 2023-02-28 02:20 . batch synchronize
#include <stdio.h>
#include <stdlib.h>
char* get_string(void)
{
int size = 0; // number of characters
int capacity = 16; // available capacity, initially 16
char* str = (char*)malloc(capacity); // pointer to the data
if (str == NULL)
{
fprintf(stderr, "malloc failed!\n");
exit(EXIT_FAILURE);
}
int ch;
while ((ch = getchar()) != '\n')
{
if (size + 1 == capacity) // need to expand capacity, be careful '\0'
{
capacity *= 2;
str = (char*)realloc(str, capacity);
if (str == NULL)
{
fprintf(stderr, "malloc failed!\n");
exit(EXIT_FAILURE);
}
}
str[size++] = ch; // append a char
}
str[size] = '\0';
return str;
}
int main(void)
{
printf("Arbitrary length string input function.\n");
while (1)
{
printf(">>> ");
char* str = get_string();
printf("input=\"%s\"\n\n", str);
free(str);
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ChobitsY/C-Code.git
git@gitee.com:ChobitsY/C-Code.git
ChobitsY
C-Code
C Code
master

Search

0d507c66 1850385 C8b1a773 1850385