P. Miguel P. Miguel - 3 months ago 21
Bash Question

Shell that reads line by line

So I'm making a very basic shell that reads stuff line by line and I'm having issues with the loops.
This is my main:

int main(int argc, char* argv[]) {
char* av[ARGVMAX];
int nArgs, i, j, k;

while ( fgets( line, LINESIZE, stdin ) != NULL && line[0] != '\n') {
for(i = 0; line[i] != '\n'; i++) {
temp[i] = line[i];
scanf("%d", &nArgs);
j = 0;
while(j<nArgs) {
temp[i++] = ' ';
scanf("%c", &temp[i++]);
makeargv(temp, av);
return 0;

First of all, what I'm trying to do is turn every singular line that is read into one whole, by other words, reading a "string" and putting it in an array, separating every word with a ' '.

Now my problem is, whenever the program is on "scanf("%c", &temp[i++])" he doesn't let me type anything on the first go, what that means is that whenever I enter the loop for the first time he kind of skips that line of code, but on the other entrances of the loop (second time or third time) he waits for me to write something.

What does this mean? Am I doing something wrong?
Thank you in advance!


After the line

scanf("%d", &nArgs);

there remains a newline in the input buffer, and this is read by the line

scanf("%c", &temp[i++]);

Although the format %d (and most formats) ignore any leading whitespace in the input buffer, %c does not, unless you insert a space like this:

scanf(" %c", &temp[i++]);
//     ^