4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ターミナルの自由な場所で入力する方法

Last updated at Posted at 2019-05-21

やりたいこと

出力した文字に続いて、入力すること。


$ ./main
Input: 〇〇〇 <◁== ここに入力

C ソースコード

main.c

# include <stdio.h>

int main(void)
{
    char buf[6] = {0};
    printf("Input: ");
    fflush(stdout);
    fgets(buf, sizeof(buf), stdin);
    puts(buf);
    return 0;
}

Rust ソースコード

main.rs

use std::io::{stdin, stdout, Read, Result, Write};

fn main() -> Result<()> {
    let mut buf = [0; 5];
    print!("Input: ");
    stdout().flush().unwrap();
    stdin().read_exact(&mut buf)?;
    println!("{}", String::from_utf8(buf.to_vec()).unwrap_or_default());
    Ok(())
}

結論

入力の直前でflushして、バッファを吐き出せばできる。

最後に

Rustでしばらく考えても分からず、一度は諦めていましたが、
Cを書いてる最中にfflush使えば、いけそうだと閃いて、成功しました。

もっと別の方法で実現する方法があれば、教えてください。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?