简体   繁体   中英

K&R C Exercise 1-18 no output/debugging issues

I wrote the code below in Code::Blocks as a response to K&R C exercise 1-18:

Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

I meant it to remove the blanks and tabs (I haven't tackled the blank line part yet). The while loop correctly saves input to the character array ip , however, the rest of the code doesn't seem to be working as EOF doesn't illicit any output at all.

#include <stdio.h>
#define MAXLINE 1000

main(){
    int c, z;
    char ip[MAXLINE];

    z = 0;

    while ((c = getchar()) != EOF) {
        ip[z] = c;
        ++z;
    }

    for (z = 0; ip[z] == ' ' || ip[z] == '\t'; ip[z] = ip[z + 1]);
    printf("%s", ip);

}

I was trying to use this issue as a way to learn the debugger, but after I add a breakpoint at line 14, open the watches window, and press the start arrow, nothing happens. No yellow arrow appears at my break point, my step options are greyed out, and neither my variable names nor their values show up in the watch window.

Advice on fixing my code is appreciated, but what I really want to know is what I'm doing or not doing that is preventing the debugger from helping me.

If you aren't seeing any output, then this is probably because your program is stuck in the for loop: for (z = 0; ip[z] ... , which happens if the string ip starts with two consecutive spaces and/or tabs.

The algorithm for removing a certain character is as such:

Have two variables that index a position in the string, destination and source. The code will be inside an outer loop. Source index will iterate in an inner loop until it finds a character that isn't one of the characters that have to be removed or the null character. Then the character from source index is assigned to destination index. The code then checks if source index reached a null character and breaks the outer loop if it did. Both indexes get incremented, the outer loop is then repeated.

In pseudo code:

remove = '\t'
string
source = 0 
destin = 0

while
    while string at source equals remove and not-equals null character
        source++
    string at destin = string at source
    if string at source equals null character
        break
    source++
    destin++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM