本文介绍了D lang-在同一程序中使用read和readln()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在D程序中遇到一个非常奇怪的问题。 read(%s,variable)本身可以正常工作,而readln(variable)本身可以正常工作,但是当我将两者放在一起时,readln()似乎被传递了。

  import std.stdio;会同时发生错误。 
import std.string;

void main()
{
int x;
write(输入数字:);
readf(%s,& x);

write(你叫什么名字?);
string name = chomp(readln());

writeln( H​​ello,name,!);
}

输出:

 输入数字:5 
您叫什么名字?你好 !

但是,如果我注释掉readf(%s,& x),则调用readln如我所愿:

 输入数字:您叫什么名字? hjl 
你好hjl!


解决方案

这是readf和scanf函数的常见错误也来自C。 readf关于格式字符串和空格非常准确。在您的字符串存在的情况下,它读取值,然后在看到的第一个空格处停止...恰好是换行符。



如果要执行以下操作:

 输入数字:123帐单

它将打印您叫什么名字?您好!! ,因为它停在了空格处,然后readln捡起它直到行尾。



如果您执行123,请按Enter,然后输入您的姓名,readf停在换行符处……readln然后以空行出现。



最简单的解决方法是告诉readf消费换行符

  readf(%s\n,& x); 

然后readln将以一个空缓冲区开始,并且能够获取所需的内容。 / p>

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!
解决方案

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.

这篇关于D lang-在同一程序中使用read和readln()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 03:52