简体   繁体   中英

How do you insert N blank spaces in text file

I have created a program that reads a file inputted by the user and

inside the file contains formatting features such as .br and .spX , where X is an integer.

so I am trying to implement these formatting features in the output.

I have made my program to break the sentence when it sees ".br" but now

I am trying to create 1 blank line when it sees ".sp" and ".sp2" it should

print two blanked lines then continue on with the text.

while ( ( fscanf ( fp, "%60s", word)) == 1) {
    if ( strcmp ( word, ".br") == 0) { // break the text when you see .br
        printf ( "%s\n", line);
        line[0] = '\0';
        out = 1;
    }

       if ( strcmp ( word, ".spn") == 0) { // insert n blank lines

    }

So for example "Hello my name is .sp2 Josh" should output:

Hello my name is 


Josh

If there are no spaces between the .sp and the integer, as in .sp4 , then strncmp could be used to compare the first three characters and then sscanf to capture the integer.

if ( strncmp ( word, ".sp", 3) == 0) {
    if ( ( sscanf ( &word[3], "%d", &blanks)) == 1) {
        printf ( "%s\n", line);
        while ( blanks) {
            blanks--;
            printf ( "\n");
        }
        line[0] = '\0';
        out = 1;
    }
    else {
        printf ( "%s\n", line);
        line[0] = '\0';
        out = 1;
    }
}

You could take advantage of the fact that fscanf formats that require a numerical conversion don't advance the file pointer when the conversion fails.

So if you encounter the string ".sp" , scan the next string for a number. If that fails, you have your default case, a single blank line. Otherwise, you have the number of spaces to print.

For example:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE *fp = fopen("josh.txt", "r");
    char word[61];
    int wc = 0;

    if (fp == NULL) {
        fprintf(stderr, "Could not open 'josh.txt'.\n");
        exit(1);
    }

    while (fscanf(fp, "%60s", word) == 1) {
        if (strcmp (word, ".br") == 0) {
            putchar('\n');
            wc = 0;

            continue;
        }

        if (strcmp (word, ".sp") == 0) {
            int n;

            if (fscanf(fp, "%d", &n) < 1 || n < 0) n = 1;

            putchar('\n');
            while (n-- > 0) putchar('\n');
            wc = 0;

            continue;
        }

        if (wc++ > 0) putchar(' ');
        printf("%s", word);
    }

    putchar('\n');
    fclose(fp);

    return 0;
}

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