获得控制台输入Cstrings [英] getting console input for Cstrings

查看:121
本文介绍了获得控制台输入Cstrings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好SO,

我工作的一个任务,我需要从控制台获取输入并保存到一个CString。一切编译罚款,但是当程序运行时,它只是跳过从用户获得的输入。所以它会输出:输入要插入的字符串:然后跳过cin.getline功能,然后执行下一个命令。

I'm working on an assignment and I need to get input from the console and save it to a cstring. Everything compiles fine, but when the program runs, it just skips over getting input from the user. So it will output: "Enter string to be inserted: " then skip the cin.getline function, then execute the next command.

下面是我的头文件,CString的申报和code,我遇到的麻烦的就行了。

Here's my header files, the declaration of the cstring, and the line of code I'm having trouble with.

#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 >> tempCStringbecaues只会得到输入到第一个空间,我需要从一切的控制台输入到新行

note: I can't use "cin >> tempCString" becaues it will only get the input up to the first space, I need to get input from the console of everything up to the newline.

感谢您

推荐答案

获得新的输入之前,尝试清除 CIN 的缓冲区:

Try clearing cin's buffer before getting new input:

#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');

请参阅我如何刷新CIN的缓冲区?

这篇关于获得控制台输入Cstrings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆