【问题标题】:Read string until new line in C++ without getline在没有getline的C ++中读取字符串直到换行
【发布时间】:2018-05-16 12:21:52
【问题描述】:

我一直在尝试制作一个程序,该程序需要我读取符号直到换行。我看到很多人在类似的问题中建议getline(),但是 我想知道是否还有其他方法可以做到这一点,主要是因为我的代码到目前为止的工作方式。

#include <iostream>
#include <string>

int main()
{
    std::string str;
    while(true)
    {
        std::cin >> str;
        std::cout << str << " ";
        //some actions with token
    }
}

我觉得这段代码有趣的是它首先读取所有输入,然后当我按下 Enter 时,它会全部写入,例如,如果我输入

1 2 3 a b c

我得到输出之后我按回车。那么有没有办法利用它来发挥我的优势并且只接受一行输入?

【问题讨论】:

  • using namespace std; is a bad practice,永远不要使用它。
  • 我通常不会,但仍然感谢您的提醒
  • "接受一行输入" - 你可能应该重新阅读格式化的输入描述。
  • @SaschaP 为什么是什么?如果您问为什么这是一种不好的做法,请点击链接...
  • @tambre 谢谢,无法识别链接!

标签: c++


【解决方案1】:

您看到输入后的输出行为很可能是由于缓冲区被刷新。在我知道的大多数情况下,这只是您如何与终端的stdout 交互的一种人工制品,根本不应该改变stdin 的读取方式。

你最好的选择肯定是istream::getlineC++ Reference 上有一个很好的例子:

// istream::getline example
#include <iostream>     // std::cin, std::cout

int main () {
  char name[256], title[256];

  std::cout << "Please, enter your name: ";
  std::cin.getline (name,256);

  std::cout << "Please, enter your favourite movie: ";
  std::cin.getline (title,256);

  std::cout << name << "'s favourite movie is " << title;

  return 0;
}

有关缓冲区刷新的更多信息,我发现了一个不错的 SO 问题:What does flushing the buffer mean?

【讨论】:

  • 链接 C++ Reference 当前指向 404 页面。
猜你喜欢
  • 1970-01-01
  • 2022-07-02
  • 2017-12-19
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2018-08-22
  • 1970-01-01
相关资源
最近更新 更多