D lang - Using read and readln() in the same program

我是研究僧i 提交于 2019-12-02 06:17:44

问题


I'm having a very strange issue with a D program. read(" %s", variable) works fine by itself and readln(variable) works fine by itself, but when I put the two together, readln() appears to be passed over. The error occurred using both gdc and dmd.

import std.stdio;
import std.string;

void main()
{
    int x;
    write("Enter a number: ");
    readf(" %s", &x);

    write("What is your name? ");
    string name=chomp(readln());

    writeln("Hello ", name, "!");
}

Output:

Enter a number: 5
What is your name? Hello !

However, if I comment out readf(" %s", &x), readln is called as I desire:

Enter a number: What is your name? hjl
Hello hjl!

回答1:


This is a common mistake with the readf and scanf function from C too. readf is pretty exact about the format string and whitespace. With your string there, it reads the value then stops at the first whitespace it sees... which happens to be the newline.

If you were to do this:

Enter a number: 123 bill

It would print What is your name? Hello bill! because it stopped at the space, then readln picked that up until end of line.

If you do 123, hit enter, then enter your name, readf stops at the newline character... which readln then picks up as an empty line.

Easiest fix is to just tell readf to consume the newline too:

readf(" %s\n", &x);

Then readln will be starting with an empty buffer and be able to get what it needs to get.



来源:https://stackoverflow.com/questions/24900467/d-lang-using-read-and-readln-in-the-same-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!