【问题标题】:getting console input for Cstrings获取 Cstrings 的控制台输入
【发布时间】:2012-03-18 00:52:39
【问题描述】:

注意:这是在 C++ 中,但使用 C 风格的字符串

你好,

我正在处理一项作业,我需要从控制台获取输入并将其保存到 cstring。一切都编译得很好,但是当程序运行时,它只是跳过了从用户那里获取输入。所以它会输出:“输入要插入的字符串:”然后跳过cin.getline函数,然后执行下一条命令。

这是我的头文件、cstring 的声明以及我遇到问题的代码行。

#include "stdafx.h"
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
  char tempCString[500] = {};

//...code snipit...

  cout << "Enter string to be inserted: " << endl;
  cin.getline(tempCString, 500, '\n'); //I've also tried cin.getline(tempCString, 500);

//...end code snipit...

  return 0;
}

注意:我不能使用“cin >> tempCString”,因为它只会获取第一个空格的输入,我需要从控制台获取所有内容的输入,直到换行符。

谢谢

【问题讨论】:

  • 如果它被跳过,很可能是您在之前的阅读中在输入缓冲区中留下了一个换行符。
  • 我将如何清除缓冲区?

标签: c++ c string cstring c-strings


【解决方案1】:

在获取新输入之前尝试清除 cin 的缓冲区:

#include <limits>

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max());
cout << "Enter string to be inserted: " << endl;
cin.getline(tempCString, sizeof(tempCString), '\n');

How do I flush the cin buffer?

【讨论】:

  • 谢谢你提醒我,我忘记了。
  • 我听说 cin 和 cin.getline() 不能很好地配合使用。现在我知道他们为什么这么说哈哈。只需在每个 cin 后面加上 cin.ignore(1000, 10) >>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 2012-01-08
相关资源
最近更新 更多