#include <stdio.h>
#define TABLENGTH 4
main()
{
int n; /* Position of cursor relative to tab stops */
int c;
n = TABLENGTH; /* Setting n to TABLENGTH is functionally equivalent to setting it to zero, but will make calculations easier */
while ((c=getchar()) != EOF) {
if (n > TABLENGTH)
n = 1; /* Should this be n = n - TABLENGTH? */
if (c != '\t') {
putchar(c);
if (c == '\n')
n = TABLENGTH; /* A newline resets the cursor to 'zero' */
else
++n;
}
else {
for (c = 0; c < n; ++c)
putchar(' ');
n = TABLENGTH; /* Tabs reset cursor to 'zero' */
}
}
return 0;
}
Newbie Question
Started by british0zzy, Jul 17 2008 06:04 PM
3 replies to this topic
#1
Posted 17 July 2008 - 06:04 PM
I'm writing a program that removes tabs from the input and replaces it with the correct number of spaces. It's giving me odd results, which I can't quite figure out why. If you could look at this short program and give me some pointers, it'd be greatly appreciated :)
|
|
|
#2
Posted 17 July 2008 - 07:16 PM
You're making this too complicated. Try this.
#include <stdio.h>
#define TABLEN 4
void main(void)
{
int ch, i;
while((ch = getchar()) != EOF)
{
if(ch == '\t')
{
for(i = 0; i < TABLEN; ++i)
putchar(' ');
}
else
putchar(ch);
}
}
#3
Posted 17 July 2008 - 07:27 PM
ok, I didn't explain the objective of the program clearly. I am assuming there are fixed tab stops every n columns. So if I the input is "12'\t'34", the output should be "12**34". Or if I typed "12345'\t'6", the output should be "12345***6". (The *'s are spaces and '\t' is obviously a tab.)
Does that make more sense?
My earlier version works perfectly except when you skip to a new line, it breaks because skipping to a newline resets the cursor to the beginning.
Here's the earlier code:
Does that make more sense?
My earlier version works perfectly except when you skip to a new line, it breaks because skipping to a newline resets the cursor to the beginning.
Here's the earlier code:
#include <stdio.h>
#define TABLENGTH 4
main()
{
int n; /* Position of cursor relative to tab stops */
int c;
n = TABLENGTH; /* Setting n to TABLENGTH is functionally equivalent to setting it to zero, but will make calculations easier */
while ((c=getchar()) != EOF) {
if (n > TABLENGTH)
n = 1; /* Should this be n = n - TABLENGTH? */
if (c != '\t') {
putchar(c);
++n;
}
else {
for (c = 0; c < n; ++c)
putchar(' ');
n = TABLENGTH; /* Tabs reset cursor to 'zero' */
}
}
return 0;
}
#4
Posted 18 July 2008 - 06:57 PM
OOOH. I see now...so I'm assuming you get n somewhere beforehand, along with some input to parse, right? If you don't want to have it reset at a newline, just add another if statement.


Sign In
Create Account

Back to top









