www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Using "%s" with inputting numberic values

reply pascal111 <judas.the.messiah.111 gmail.com> writes:
In the next code, we used "%s" format with receiving an integer 
value, while from C experience, we know that we use "%d" or "%i" 
formats, so what "%s" stands for here, I guess it's for receiving 
string data type?

import std.stdio;

     void main() {
         write("How many students are there? ");

         /* The definition of the variable that will be used to
          * store the information that is read from the input. */
         int studentCount;

         // Storing the input data to that variable
         readf("%s", &studentCount);

         writeln("Got it: There are ", studentCount, " students.");
     }
Jul 24 2022
parent reply Adam D Ruppe <destructionator gmail.com> writes:
On Sunday, 24 July 2022 at 23:12:46 UTC, pascal111 wrote:
 In the next code, we used "%s" format with receiving an integer 
 value, while from C experience, we know that we use "%d" or 
 "%i" formats, so what "%s" stands for here, I guess it's for 
 receiving string data type?
The D things in std.stdio, writef and readf, use %s to just mean default for the given type. Since you passed it an int, the function knows it got an int (this is different than C, where the function only knows the format string so it requires you to get it right) and just automatically picks a default representation to scan. You can writef("%s %s", "foo", 5); and it will see "foo" is a string and thus do it as a regular %s then see 5 is an int and since it knows, and you asked for just the default as-string representation, it will convert just like %d would.
Jul 24 2022
parent pascal111 <judas.the.messiah.111 gmail.com> writes:
On Sunday, 24 July 2022 at 23:48:59 UTC, Adam D Ruppe wrote:
 On Sunday, 24 July 2022 at 23:12:46 UTC, pascal111 wrote:
 [...]
The D things in std.stdio, writef and readf, use %s to just mean default for the given type. Since you passed it an int, the function knows it got an int (this is different than C, where the function only knows the format string so it requires you to get it right) and just automatically picks a default representation to scan. You can writef("%s %s", "foo", 5); and it will see "foo" is a string and thus do it as a regular %s then see 5 is an int and since it knows, and you asked for just the default as-string representation, it will convert just like %d would.
It's like an automatic figuring for the data type.
Jul 24 2022