在C程序中未完全解析数组
我试图构建一个程序,从输入中解析一个字符数组,然后返回一个忽略额外空格的格式化字符串在C程序中未完全解析数组,c,arrays,stdio,C,Arrays,Stdio,我试图构建一个程序,从输入中解析一个字符数组,然后返回一个忽略额外空格的格式化字符串 #include <stdio.h> # include <ctype.h> /* count charecters in input; 1st version */ int main(void) { int ch, outp=0; char str[1000], nstr[1000]; /* collect the data string */ while ((ch
#include <stdio.h>
# include <ctype.h>
/* count charecters in input; 1st version */
int main(void)
{
int ch, outp=0;
char str[1000], nstr[1000];
/* collect the data string */
while ((ch = getchar()) != EOF && outp < 1000){
str[outp] = ch;
outp++;
}
for (int j = 0; j < outp-1; j++){
printf("%c",str[j]);
}
printf("\n");
for (int q = 0; q < outp-1; q++)
{
if (isalpha(str[q]) && isspace(str[q+1])){
for(int i = 0; i < outp; i++){
if (isspace(str[i]) && isspace(i+1)){
continue;
}
nstr[i] = str[i];
}
}
}
printf("\n");
printf("Formated Text: ");
for (int i = 0; i < outp-1; i++){
printf("%c", nstr[i]);
}
//putchar("\n");c
// printf("1");
return 0;
}
#包括
#包括
/*计算输入中的字符数;第一版*/
内部主(空)
{
int-ch,输出=0;
char-str[1000],nstr[1000];
/*收集数据字符串*/
while((ch=getchar())!=EOF&&outp<1000){
str[outp]=ch;
outp++;
}
对于(int j=0;j
这是我的密码。数组从未被完全解析,结尾通常被省略,出现奇数字符,并且过去的尝试产生了一个未被完全解析的数组,为什么?
这是“C编程语言”的练习1-9 a)将字符从str
复制到nstr
时,需要使用额外的索引变量。做点像-
for(int i = 0, j = 0; i < outp -1; i++){
if (isspace(str[i]) && isspace(i+1)){
continue;
}
nstr[j++] = str[i];
}
for(inti=0,j=0;i
b) 打印nstr
时,使用的是原始字符串的长度str
。由于已删除空格,因此nstr
的长度将小于str
的长度
您需要立即找到
nstr
的长度,或者在条件中使用i
nstr
中的字符数可能比str
中的要少得多。但是您仍然从nstr
输出outp-1
字符,这可能导致打印nstr
的未初始化(和不确定)部分。删除空格的逻辑不正确,因为一旦跳过额外的空格,就需要将字符复制到不同的位置。因此,您需要一个额外的索引,该索引仅在复制字符时递增。然后,您必须确保复制了最后一个字符(如果它不是精简的空格)。这些数组上没有空终止符,因此使用strlen()
不是一个好主意,而且您对最后一个字符有问题,因为您检查了后面的字符。现在仍然没有-现在您没有复制最后一个字符。建议您使用一些相关数据进行测试,但您似乎没有这样做。