Inuart
Inuart

Reputation: 1512

two spaces as scanf delimeter

I was hoping to be able to scan a string with this format

"hello world        !!!!"

to

{"hello world", "!!!!"}

This 2 strings are separated with more than 1 space. Can I parse this or at least detect 2 consecutive spaces in scanf?

Upvotes: 0

Views: 299

Answers (3)

MOHAMED
MOHAMED

Reputation: 43558

This code could help you

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

int main()
{
    char a_buf[5][100] = {0}, sep[3] ,*buf = a_buf[0];
    int i = 0;
    buf = a_buf[0];
    while (scanf("%s%2[ ]",buf,sep) > 1) {
        if (strlen(sep)==1)
        {
            buf += strlen(buf);
            *buf++ = ' ';
        }
        else
            buf = a_buf[++i];
    }
}

Upvotes: 2

Loris1634
Loris1634

Reputation: 659

According to the c++ reference ( http://www.cplusplus.com/reference/cstdio/scanf/ )

the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

I think you should use gets: http://www.cplusplus.com/reference/cstdio/gets/ and then parse the string returned.

EDIT. Use fgets(), not gets()

Upvotes: -1

Shahbaz
Shahbaz

Reputation: 47563

From your question, it seems like you are not interested in the fact that there are more than one spaces, but just for a way to parse them.

Fear not! A single space character in *scanf already ignores all whitespace (including '\n', '\r', '\t' and '\v' in "C" locale). So in the simplest form, you could read like this:

scanf("%s %s", str1, str2);

Of course, you would need error checking. One safe way would be:

char str1[100];
char str2[100];

scanf("%99s", str1);
ungetc('x', stdin);
scanf("%*s");

scanf("%99s", str2);
ungetc('x', stdin);
scanf("%*s");

Which is a generally safe way (not related to your particular question).

The ungetc + scanf("%*s") ignore what is left of the string (if any). Note that you wouldn't need any space before the second scanf("%99s") because scanf already ignores all whitespace before %s (and in fact before all %* except %c and %[).


If you really want to make sure there are at least two spaces, and you insist on using scanf, you could do like this:

    char str1[100];
    char str2[100];
    char c;

    scanf("%99s", str1);
    ungetc('x', stdin);
    scanf("%*s");

    scanf("%c", &c);
    if (c != ' ')
        goto exit_not_two_spaces;
    scanf("%c", &c);
    if (c != ' ')
        goto exit_not_two_spaces;

    scanf("%99s", str2);
    ungetc('x', stdin);
    scanf("%*s");

    return /* success */
exit_not_two_spaces:
    ungetc(c, stdin);
    return /* fail */

Upvotes: 2

Related Questions