formattedRead whitespace quirks (compared to scanf)
Gordon
me at home.com
Wed Dec 25 12:43:24 PST 2013
Hello,
Trying to use "std.file.slurp" as generic file loader,
I encountered a quirk in the way formattedRead works compared to
the (standard?) scanf.
It seems using "%s" format does not stop at whitespace if the
"%s" is the last item in the format string.
A simple comparison would be:
-- in C --
char a[100] = {0};
chat *input = "hello world 42";
sscanf(input, "%s", &a);
-- in D --
string a;
string input = "hello world 42";
formattedRead(input,"%s", &a);
-----------
In "C", the variable "a" would contain only "hello";
In "D", the variable "a" would contain "hello world 42";
BUT,
If the format string would be "%s %s %d" (and we had three
variables), then "formattedRead()" would behave exactly like
"sscanf()".
Complete code to illustrate the issue:
-- scanf_test.c --
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *text = "hello world 42";
char a[100] = {0};
char b[100] = {0};
char c[100] = {0};
int pos=0;
sscanf(text,"%s %s %s", &a, &b, &c);
printf("reading all-at-once: a='%s' b='%s' c='%s'\n",
a,b,c);
sscanf(text,"%s%n", &a, &pos);
printf("reading first word: a='%s' (remaining
text='%s')\n",a,text+pos);
}
------------------
--- formattedread_test.d ---
import std.string;
import std.format;
import std.stdio;
void main()
{
string a,b,c;
string text = "hello world 42";
formattedRead(text,"%s %s %s", &a, &b, &c);
writeln("reading all-at-once: a = '",a,"' b='",b,"'
c='",c,"'");
text = "hello world 42";
formattedRead(text, "%s", &a);
writeln("reading first word: a = '",a,"' remaining
text='",text,"'");
}
----------------------------
The output:
$ gcc -o scanf_test scanf_test.c
$ ./scanf_test
reading all-at-once: a='hello' b='world' c='42'
reading first word: a='hello' (remaining text=' world 42')
$ rdmd formattedread_test.d
reading all-at-once: a = 'hello' b='world' c='42'
reading first word: a = 'hello world 42' remaining text=''
More information about the Digitalmars-d
mailing list