I am trying to build a program that parses an array of chars from input and then returns a formatted omitting extra whites spaces.
#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;
}
Here is my code. The array is never fully parsed, the end is usually omitted, odd chars show up and past attempts have yielded a not fully parsed array, Why? This is exercise 1-9 from "the C programming language".
a) You need to use an additional index variable while copying the characters from str
to nstr
. Do something like -
for(int i = 0, j = 0; i < outp -1; i++){
if (isspace(str[i]) && isspace(i+1)){
continue;
}
nstr[j++] = str[i];
}
b) While you are printing nstr
, you are using the length of the original string str
. The length of nstr
will be less than that of str
since you have removed the spaces.
You need to find the length of nstr
now or use i < strlen(nstr) -1
in the condition.