简体   繁体   English

C ++ cin.getline仅读取一个字符

[英]C++ cin.getline only reads one character

I'm using Xcode 4.5 and I have the following code in my program: 我正在使用Xcode 4.5,程序中包含以下代码:

char strChar[5];
cin.getline(strChar, 5);
int i = atoi(strChar);

When I start to try and enter a number, after the first number is pressed, the console will not accept any more input (other than the enter key, in which case the program just returns zero straight away). 当我开始尝试输入一个数字时,在按下第一个数字之后,控制台将不再接受任何输入(除了回车键之外,在这种情况下,程序将立即返回零)。 Obviously, I want to accept more than one character, how can I accomplish this? 显然,我想接受多个字符,我该怎么做?

Thanks for answering my question 谢谢回答我的问题

If you want to read one line, it's probably easier to write: std::getline(std::cin, str), where str is of type std::string. 如果您想读一行,可能更容易编写:std :: getline(std :: cin,str),其中str的类型为std :: string。 Your example reads only 5 characters. 您的示例仅读取5个字符。

Note: If you want to read not just 1 number, but a bunch of numbers on multiple lines, you should put this all into a loop. 注意:如果您不仅要读取一个数字,而且要读取多行中的一堆数字,则应将所有这些内容放入一个循环中。

*******UPDATE*********** 10/04/2012********* *******更新*********** 2012年10月4日*********

APPLE HAS RELEASED AN UPDATE THAT FIXES THIS ISSUE. APPLE已发布可解决此问题的更新。 XCODE 4.5.1 (4G1004) XCODE 4.5.1(4G1004)

This is a known bug in Xcodes newest release (4.5). 这是Xcodes最新版本(4.5)中的一个已知错误。 Apple knows about it and is working on a patch. 苹果对此有所了解并正在开发补丁。 Currently at press time, there is no known work around. 目前,截至发稿时,尚无已知的解决方法。 For now you just have to run the program in Terminal. 现在,您只需要在Terminal中运行该程序。

** Note in newer versions of Xcode, the command line tools are not installed automatically ** To Install Go Into Xcode -> Preferences -> Downloads -> Install the command line tools **请注意,在较新版本的Xcode中,不会自动安装命令行工具**要安装,请进入Xcode->首选项->下载-> 安装命令行工具

To Run C++ Programs in Terminal: 要在终端中运行C ++程序:

1.) Open Terminal. 1.)打开终端。

2.) Navigate to the correct directory 2.)导航到正确的目录

3.) type "make projectName" minus the quotes 3.)输入“ make projectName”减去引号

4.) Execute Program: "./projectName" minus the quotes 4.)执行程序:“ ./ projectName”减去引号

请注意:您的代码没有将字符串读入“ str”,而只是读入“ strChar”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM