字符串数据输入和存储 [英] String data input and storage

查看:91
本文介绍了字符串数据输入和存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我对以下代码段有两个问题。我试图在一系列字符串中读取
并将它们保存到字符数组中。因为我不知道我的字符串将会有多长(并且我不想通过为所有输入字符串分配1000的数组来浪费
内存)I

根据字符串的长度自行分配内存。


char * inputData;

char line [200];


printf(" Input:");

fgets(line,sizeof(line),stdin);


line [strlen(line)-1] =''\''';


inputData = malloc(strlen(line)* sizeof(inputData));


if(inputData == NULL){

fprintf(stderr," malloc failed!\ n");

退出(EXIT_FAILURE);

}


strcpy(inputData,line);

/ *无论我对字符串做什么* /

免费(inputData);


1.这是正确的方法吗?还是有更好/更简单的方法?


2.我从字符串中删除''\0''。有效还是无效?


谢谢,

克里斯

Hi,

I have two questions about the following code snippet. I am trying to
read in a series of strings and save them to character arrays. Since I
dont know how long my string is going to be (and I dont want to waste
memory by allocating an array of 1000 for all the input strings) I
allocate the memory myself according to the length of the string.

char *inputData;
char line[200];

printf("Input: ");
fgets(line, sizeof(line), stdin);

line[strlen(line)-1] = ''\0'';

inputData = malloc(strlen(line)*sizeof(inputData));

if (inputData == NULL){
fprintf(stderr, "malloc failed!\n");
exit(EXIT_FAILURE);
}

strcpy(inputData, line);
/* do whatever i do with the strings*/
free(inputData);

1. Is this the right way to do this or is there a better/an easier way?

2. I am removing the ''\0'' from the string. Valid or invalid?

Thanks,
Chris

推荐答案

Christoph Scholtes写道:
Christoph Scholtes wrote:

您好,

我对以下代码片段有两个疑问。我试图读取一系列字符串并将它们保存到字符数组中。因为我不知道我的字符串会有多长(并且我不想通过为所有输入字符串分配1000的数组来浪费内存)我自己分配内存到字符串的长度。

Hi,

I have two questions about the following code snippet. I am trying to
read in a series of strings and save them to character arrays. Since I
dont know how long my string is going to be (and I dont want to waste
memory by allocating an array of 1000 for all the input strings) I
allocate the memory myself according to the length of the string.




我为此目的使用链表。


/ * BEGIN line_to_string.c * /


#include< stdio.h>

#include< stdlib.h>

#include< limits.h>

#include< string.h>


struct list_node {

struct list_node * next;

void * data;

};


int line_to_string(FILE * fp,char ** line,size_t * size);

void list_free(struct list_node * node,void(* free_data)(void *));

void list_fprint(FILE * stream,struct list_node * node);

struct list_node * string_node(struct list_node ** head,

struct list_node * tail,

char * data);


int main(vo id)

{

struct list_node * head,* tail;

int rc;

char * buff_ptr;

size_t buff_size;

long unsigned line_count;


puts(

" \ nThis程序制作并打印从标准输入流输入的文本的所有行的列表。\ n"

" Just hit the输入键结束,\ n"

"或输入任意一行字符继续。

);

tail = head = NULL;

line_count = 0;

buff_size = 0;

buff_ptr = NULL;

rc = line_to_string(stdin,& buff_ptr,& buff_size);

while(rc> 1){

++ line_count;

tail = string_node(& head,tail,buff_ptr);

if(tail == NULL ){

休息;

}

put(

" \ n只需点击Enter键即可结束,\ n"

"或输入任何其他字符行继续。

);

rc = line_to_string(stdin ,& buff_ptr,& buff_size);

}

开关(rc){

案例EOF:

if(buff_ptr!= NULL&& strlen(buff_ptr)> 0){

puts(" rc equals EOF \\\
buff_ptr中的字符串是:");

puts(buff_ptr);

++ line_count;

tail = string_node(& head,tail,buff_ptr);

}

休息;

案例0:

puts(realloc返回空指针值);

if(buff_size> 1){

puts(" rc equals 0 \\\
buff_ptr中的字符串是:");

puts(buff_ptr);

++ line_count;

tail = string_node(& head,tail,buff_ptr);

}

break;

默认值:

如果(line_count!= 0&& tail == NULL){

puts(节点分配失败。);

puts("输入的最后一行没有进入list:");

puts(buff_ptr);

}

free(buff_ptr);

puts (\行缓冲区已被释放。\ n);

printf(输入%lu行文字。\ nn,line_count);

puts(它们是:\ n);

list_fprint(stdout,head);

list_free(head,free);

puts(\ n列表已被释放。\ n);

返回0;

}

int line_to_string(FILE * fp,char ** line,size_t * size)

{

int rc;

void * p;

size_t count;


count = 0;

for(rc = getc(fp); rc!= EOF; rc = getc(fp)){

++ count;

if(count + 2> * size){

p = realloc(* line,count + 2);

if(p == NULL){

if(* size>计数){

(* line)[count] =''\''';

(* line)[count - 1] =(char)rc;

}否则{

ungetc(rc,fp);

}

count = 0;

休息;

}

* line = p;

* size = count + 2;

}

if(rc ==''\ n''){

(* line)[count - 1] =''\''' ;

休息;

}

(*行)[count - 1] =(char)rc;

}

if(rc!= EOF){

rc = count> INT_MAX? INT_MAX:count;

} else {

if(* size> count){

(* line)[count] ='' \ 0'';

}

}

返回rc;

}


void list_free(struct list_node * node,void(* free_data)(void *))

{

struct list_node * next_node;


while(node!= NULL){

next_node = node - >下一个;

free_data(节点 - >数据);

免费(节点);

node = next_node;

}

}


void list_fprint(FILE * stream,struct list_node * node)

{

while(node!= NULL){

fputs(node - > data,stream);

putc(''\ n'',stream) ;

node = node - >下一个;

}

}


struct list_node * string_node(struct list_node ** head,

struct list_node * tail,

char * data)

{

struct list_node * node;


node = malloc(sizeof * node);

if(node!= NULL){

node - > next = NULL;

node - > data = malloc(strlen(data)+ 1);

if(node - > data!= NULL){

if(* head == NULL){

* head = node;

} else {

tail - > next = node;

}

strcpy(节点 - >数据,数据);

}其他{

free(节点);

node = NULL;

}

}

返回节点;

}


/ * END line_to_string.c * /

-

pete



I use a linked list for that purpose.

/* BEGIN line_to_string.c */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

struct list_node {
struct list_node *next;
void *data;
};

int line_to_string(FILE *fp, char **line, size_t *size);
void list_free(struct list_node *node, void (*free_data)(void *));
void list_fprint(FILE *stream, struct list_node *node);
struct list_node *string_node(struct list_node **head,
struct list_node *tail,
char *data);

int main(void)
{
struct list_node *head, *tail;
int rc;
char *buff_ptr;
size_t buff_size;
long unsigned line_count;

puts(
"\nThis program makes and prints a list of all the lines\n"
"of text entered from the standard input stream.\n"
"Just hit the Enter key to end,\n"
"or enter any line of characters to continue."
);
tail = head = NULL;
line_count = 0;
buff_size = 0;
buff_ptr = NULL;
rc = line_to_string(stdin, &buff_ptr, &buff_size);
while (rc > 1) {
++line_count;
tail = string_node(&head, tail, buff_ptr);
if (tail == NULL) {
break;
}
puts(
"\nJust hit the Enter key to end,\n"
"or enter any other line of characters to continue."
);
rc = line_to_string(stdin, &buff_ptr, &buff_size);
}
switch (rc) {
case EOF:
if (buff_ptr != NULL && strlen(buff_ptr) > 0) {
puts("rc equals EOF\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&head, tail, buff_ptr);
}
break;
case 0:
puts("realloc returned a null pointer value");
if (buff_size > 1) {
puts("rc equals 0\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&head, tail, buff_ptr);
}
break;
default:
break;
}
if (line_count != 0 && tail == NULL) {
puts("Node allocation failed.");
puts("The last line entered didnt''t make it onto the list:");
puts(buff_ptr);
}
free(buff_ptr);
puts("\nThe line buffer has been freed.\n");
printf("%lu lines of text were entered.\n", line_count);
puts("They are:\n");
list_fprint(stdout, head);
list_free(head, free);
puts("\nThe list has been freed.\n");
return 0;
}

int line_to_string(FILE *fp, char **line, size_t *size)
{
int rc;
void *p;
size_t count;

count = 0;
for (rc = getc(fp); rc != EOF; rc = getc(fp)) {
++count;
if (count + 2 > *size) {
p = realloc(*line, count + 2);
if (p == NULL) {
if (*size > count) {
(*line)[count] = ''\0'';
(*line)[count - 1] = (char)rc;
} else {
ungetc(rc, fp);
}
count = 0;
break;
}
*line = p;
*size = count + 2;
}
if (rc == ''\n'') {
(*line)[count - 1] = ''\0'';
break;
}
(*line)[count - 1] = (char)rc;
}
if (rc != EOF) {
rc = count > INT_MAX ? INT_MAX : count;
} else {
if (*size > count) {
(*line)[count] = ''\0'';
}
}
return rc;
}

void list_free(struct list_node *node, void (*free_data)(void *))
{
struct list_node *next_node;

while (node != NULL) {
next_node = node -> next;
free_data(node -> data);
free(node);
node = next_node;
}
}

void list_fprint(FILE *stream, struct list_node *node)
{
while (node != NULL) {
fputs(node -> data, stream);
putc(''\n'', stream);
node = node -> next;
}
}

struct list_node *string_node(struct list_node **head,
struct list_node *tail,
char *data)
{
struct list_node *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -> next = NULL;
node -> data = malloc(strlen(data) + 1);
if (node -> data != NULL) {
if (*head == NULL) {
*head = node;
} else {
tail -> next = node;
}
strcpy(node -> data, data);
} else {
free(node);
node = NULL;
}
}
return node;
}

/* END line_to_string.c */
--
pete


Christoph Scholtes(在zg*********************@fe05.news.easynews.com)

说:


|我有两个关于以下代码段的问题。我正在尝试

|读入一系列字符串并将它们保存到字符数组中。

|因为我不知道我的字符串将会有多长(并且我不希望
|想通过为所有

|输入字符串分配1000的数组来浪费内存)我根据长度

|自行分配内存字符串。

|

| char * inputData;

| char line [200];

|

| printf(" Input:");

| fgets(line,sizeof(line),stdin);

|

| line [strlen(line)-1] =''\ 0'';

|

| inputData = malloc(strlen(line)* sizeof(inputData));


/ * :* / inputData = malloc(1 + strlen(行) )); / *? * /


|

| if(inputData == NULL){

| fprintf(stderr,malloc failed!\ n);

|退出(EXIT_FAILURE);

| }

|

| strcpy(inputData,line);

| / *做任何我用字符串* /

|免费(inputData);

|

| 1.这是正确的方法,还是更好/更容易

|方式?


更好/更容易取决于问题背景和你的技能。查克

Falconer,理查德希思菲尔德,我已经实现了功能

输入可变长度的字符串(当然我喜欢我的最好:-) -

我的代码位于以下链接。)


| 2.我从字符串中删除''\0''。有效还是无效?


这是有效的;但是它将''字符串'变成了一个简单的''字符数组'。

如果这就是你想要的那么它就没事了。

-

Morris Dovey

DeSoto Solar

德索托,爱荷华州美国
http://www.iedu.com/mrd/c/getsm.c
Christoph Scholtes (in zg*********************@fe05.news.easynews.com)
said:

| I have two questions about the following code snippet. I am trying
| to read in a series of strings and save them to character arrays.
| Since I dont know how long my string is going to be (and I dont
| want to waste memory by allocating an array of 1000 for all the
| input strings) I allocate the memory myself according to the length
| of the string.
|
| char *inputData;
| char line[200];
|
| printf("Input: ");
| fgets(line, sizeof(line), stdin);
|
| line[strlen(line)-1] = ''\0'';
|
| inputData = malloc(strlen(line)*sizeof(inputData));

/* How about: */ inputData = malloc(1+strlen(line)); /* ? */

|
| if (inputData == NULL){
| fprintf(stderr, "malloc failed!\n");
| exit(EXIT_FAILURE);
| }
|
| strcpy(inputData, line);
| /* do whatever i do with the strings*/
| free(inputData);
|
| 1. Is this the right way to do this or is there a better/an easier
| way?

Better/easier depends on the problem context and your skills. Chuck
Falconer, Richard Heathfield, and I have all implemented functions
that input variable-length strings (I like mine best, of course :-) -
my code is at the link below.)

| 2. I am removing the ''\0'' from the string. Valid or invalid?

It''s valid; but it turns the ''string'' into a simple ''array of char''.
If that''s what you want then it''s fine.

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/mrd/c/getsm.c


Chris,

两个问题/假设。首先,你说你要阅读一个严重的字符串,但这个代码片段只能读一次。我要去

来假设这个片段周围有一个循环。第二,

取决于/ *做什么用字符串做什么* /实际上

你的实现方法是否会改变。在你做任何事情之后

你保留字符串并阅读另一个吗?
Chris,
Two questions/assumptions. First, you say you''re going to read a
serious of strings, but this code snippet only reads once. I''m going
to assume that there''s a loop surronding the snippet. Second,
depending on what "/* do whatever i do with the strings*/" actually
does your implementation method could change. After you "do whatever"
are you retaining the string and reading another?
从我可以告诉你使用多余的字符串缓冲区。您将
读入line,复制到inputData,但不要使用line和line。再次。如果

你没有再次使用这个缓冲区,你就不需要复制它了。


-Mark

Christoph Scholtes写道:

我对以下代码片段有两个问题。我试图读取一系列字符串并将它们保存到字符数组中。因为我不知道我的字符串会有多长(并且我不想通过为所有输入字符串分配1000的数组来浪费内存)我自己分配内存字符串的长度。

char * inputData;
字符行[200];

printf(" Input:");
fgets(line,sizeof(line),stdin);

line [strlen(line)-1] =''\ 0'';

inputData = malloc (strlen(line)* sizeof(inputData));

if(inputData == NULL){
fprintf(stderr," malloc failed!\ n");
退出(EXIT_FAILURE);
}

strcpy(inputData,line);
/ *做任何我用字符串做的事情* /
free(inputData);

1.这是正确的方法吗?还是有更好/更简单的方法?

2.我正在删除''\0''字符串。有效还是无效?

谢谢,
Chris
From what I can tell your using redundant string buffers. You read into "line", copy to "inputData", but don''t use "line" again. If
you''re not using this buffer again you have not need to copy out of it.

-Mark
Christoph Scholtes wrote: Hi,

I have two questions about the following code snippet. I am trying to
read in a series of strings and save them to character arrays. Since I
dont know how long my string is going to be (and I dont want to waste
memory by allocating an array of 1000 for all the input strings) I
allocate the memory myself according to the length of the string.

char *inputData;
char line[200];

printf("Input: ");
fgets(line, sizeof(line), stdin);

line[strlen(line)-1] = ''\0'';

inputData = malloc(strlen(line)*sizeof(inputData));

if (inputData == NULL){
fprintf(stderr, "malloc failed!\n");
exit(EXIT_FAILURE);
}

strcpy(inputData, line);
/* do whatever i do with the strings*/
free(inputData);

1. Is this the right way to do this or is there a better/an easier way?

2. I am removing the ''\0'' from the string. Valid or invalid?

Thanks,
Chris






这篇关于字符串数据输入和存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆