我是新成员。现在,我正在练习:“输入一串字符(100,101,102 ...)(字符数不限),并将数字存储在数组中”。我的老师提供给我们一个功能。它是ReadWord读取字符串中的数字。但我仍然有2个问题。第一,在“for”循环中,当我把“puts”命令打印出数组的元素时,我无法打印最后一个元素。如果我把“puts”命令放在“for”循环之外,我不能打印任何元素。请告诉我为什么以及如何修复它。非常感谢你!如何输入字符串(100,101,102 .....)(字符数量无限制)并将数字存储在数组中C
#include <stdio.h>
#include <string.h>
#include<conio.h>
const int MAX_NUM_LEN = 7;
const int MAX_LINE_LEN = 50;
int IsComma(int ch) {
return (ch == ',');
}
int ReadWord(char *num) {
int ch, pos = 0;
ch = getchar();
while (IsComma(ch))
ch = getchar();
while (!IsComma(ch) && (ch != EOF)) {
if (pos < MAX_NUM_LEN) {
num[pos] = (char)ch;
pos++;
}
ch = getchar();
}
num[pos] = '\0';
return pos;
}
int main()
{
int i,j;
int count;
char **ds;
ds=new char *[50];
for (i=0;i<50;i++) ds[i]=new char [3];
char num[MAX_NUM_LEN + 1];
int numLen;
char line[MAX_LINE_LEN + 1];
int lineLen = 0;
i=0;count=0;
for (;;) {
numLen = ReadWord(num);
if (numLen == 0) break;
strcpy(ds[i],num);
puts(ds[i]);
i++;
}
j=i;
printf("\n %d",j);
for(i=0;i<j;i++) printf("%s ",ds[i]);
for(i=0;i<j;i++) delete ds[i];
delete []ds;
getch();
}
C?真? 'ds = new char * [50];'?另外,你最好通过'indent'来管理你的代码,以免呕吐。 – 2013-03-16 16:29:44
将其重新标记为C++。这不是C语法 – 2013-03-16 16:32:36
请说出你输入的内容,以及你看到的输出内容。 '无法打印最后一个元素'不是很有帮助。你有一些错误,但最明显的是'new char [3]'不够大。 – john 2013-03-16 16:38:44