I have read a few lines of text into an array of C-strings. The lines have an arbitrary number of tab or space-delimited columns, and I am trying to figure out how to remove
Here's an alternative function that squeezes out repeated space characters, as defined by isspace()
in <ctype.h>
. It returns the length of the 'squidged' string.
#include <ctype.h>
size_t squidge(char *str)
{
char *dst = str;
char *src = str;
char c;
while ((c = *src++) != '\0')
{
if (isspace(c))
{
*dst++ = ' ';
while ((c = *src++) != '\0' && isspace(c))
;
if (c == '\0')
break;
}
*dst++ = c;
}
*dst = '\0';
return(dst - str);
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char buffer[256];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
size_t len = strlen(buffer);
if (len > 0)
buffer[--len] = '\0';
printf("Before: %zd <<%s>>\n", len, buffer);
len = squidge(buffer);
printf("After: %zd <<%s>>\n", len, buffer);
}
return(0);
}
The following code simply takes input character wise, then check for each character if there is space more than once it skips it else it prints the character. Same logic you can use for tab also. Hope it helps in solving your problem. If there is any problem with this code please let me know.
int c, count = 0;
printf ("Please enter your sentence\n");
while ( ( c = getchar() ) != EOF ) {
if ( c != ' ' ) {
putchar ( c );
count = 0;
}
else {
count ++;
if ( count > 1 )
; /* Empty if body */
else
putchar ( c );
}
}
}
You could read a line then scan it to find the start of each column. Then use the column data however you'd like.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_COL 3
#define MAX_REC 512
int main (void)
{
FILE *input;
char record[MAX_REC + 1];
char *scan;
const char *recEnd;
char *columns[MAX_COL] = { 0 };
int colCnt;
input = fopen("input.txt", "r");
while (fgets(record, sizeof(record), input) != NULL)
{
memset(columns, 0, sizeof(columns)); // reset column start pointers
scan = record;
recEnd = record + strlen(record);
for (colCnt = 0; colCnt < MAX_COL; colCnt++ )
{
while (scan < recEnd && isspace(*scan)) { scan++; } // bypass whitespace
if (scan == recEnd) { break; }
columns[colCnt] = scan; // save column start
while (scan < recEnd && !isspace(*scan)) { scan++; } // bypass column word
*scan++ = '\0';
}
if (colCnt > 0)
{
printf("%s", columns[0]);
for (int i = 1; i < colCnt; i++)
{
printf("#%s", columns[i]);
}
printf("\n");
}
}
fclose(input);
}
Note, the code could still use some robust-ification: check for file errors w/ferror; ensure eof was hit w/feof; ensure entire record (all column data) was processed. It could also be made more flexible by using a linked list instead of a fixed array and could be modified to not assume each column only contains a single word (as long as the columns are delimited by a specific character).