Reputation: 13
I'm trying to teach myself C, as you've probably heard so many times, and I cannot figure out what I am doing wrong. The point of the exercise I'm doing is to replace tabs with a specified number of spaces. It's supposed to be a mimic of the unix command expand. Here's what I have so far:
#include <stdio.h>
int main (int argc, char *argv[])
{
int spacecount = atoi(argv[2]);
int i, d, b, g, toput;
char string[1000];
for (d = 0, b = 0; (string[d + b] = getchar()) != EOF; d++) {
if (string[d + b] = '\t') {
toput = d % spacecount;
for (i = 0; i < toput; i++) {
if (string[d + b] = '\n')
i = toput;
string[d + b] = ' ';
b++;
}
}
}
g = d;
putchar('\n');
for (d = 0; d < g; d++)
putchar(string[d]);
putchar('\n');
}
I run it and will start typing, finish by hitting ctrl + d, (because I'm using GNU/Linux) and let it print garbage characters. I have tried the same second for loop with another string, one that has been assigned getchar() in a for loop without an if statement, and it prints non-garbage characters. I guess I am really confused. What am I doing wrong?
Upvotes: 1
Views: 499
Reputation: 54672
The problem is you are comparing the using =
operator instead of ==
. =
is a asign operator you can not use it to compare two elements.
so use
if (string[d + b] == '\t')
instead of
if (string[d + b] = '\t')
Also use
if (string[d + b] == '\n')
instead of
if (string[d + b] = '\n')
Upvotes: 0
Reputation: 213296
Enable warnings in your compiler, it really should give you a warning for this code.
(string[d + b] = '\t')
should be (string[d + b] == '\t')
.
Compile with gcc -std=c99 -pedantic-errors -Wall
.
Upvotes: 3