C语言-输入任意个字符串

来源网站:

==== http://bbs.csdn.net/topics/391045349?page=1#post-399279449


方法一:

//输入任意个字符串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE 5

int main()
{
	int i = 0, n = LINE;
	int l, len;
	char **str;
	char buf[256];    //每个字符串256个字符够吗?

	//分配原始内存大小
	if (NULL == (str =(char **)malloc(sizeof(char*)*n)))
	{
		fprintf(stderr, "can not malloc(%d*%d)\n", sizeof(char*), n);
		return 1;
	}
	printf("请输入字符串:(字符串间换行,两个换行结束输入)\n");
	while (1)
	{
		//输入字符串
		fgets(buf, 100, stdin);
		if ('\n' == buf[0]) break;     //读入空行,结束
		//内存已满,扩充
		if (i == n)
		{
			n += LINE;
			if (NULL == (str =(char **) realloc(str, sizeof(char*)*n)))
			{
				fprintf(stderr, "can not realloc(%d*%d)\n", sizeof(char*), n);
				return 1;
			}
		}
		len = strlen(buf);
		buf[len - 1] = 0;  //去'\n'
		if (NULL == (str[i] =(char *)malloc(len - 1)))
		{
			fprintf(stderr, "can not malloc(%d)\n", len - 1);
			return 1;
		}
		strcpy(str[i], buf);
		i++;
	}
	//打印
	printf("\n 你输入的字符串是:\n");
	for (l = 0; l < i; l++) 
		printf("%s\n", str[l]);

	system("pause");
	return 0;
}

方法二:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
int main()
{
	char *str=NULL,**strs=NULL,*p;
	unsigned int str_size=0,strs_size=0,i;
	do
	{
		char *tmp=(char*)realloc(str,++str_size*sizeof(char));
		if(!tmp)
		{
			free(str);
			fputs("out of memory",stderr);
			return 1;
		}
		str=tmp;
		str[str_size-1]=getchar();
	}while(str[str_size-1]!='\n');
	str[str_size-1]=0;
	for(p=strtok(str," \t");p;p=strtok(NULL," \t")) {
		char **tmp=(char**)realloc(strs,++strs_size*sizeof(char*));
		if(!tmp)
		{
			free(str);
			free(strs);
			fputs("out of memory",stderr);
			return 1;
		}
		strs=tmp;
		strs[strs_size-1]=p;
	}
	for(i=0;i<strs_size;++i)
		printf("%u:%s\n",i+1,strs[i]);
	free(strs);
	free(str);
	return 0;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。