如果用户在没有输入的情况下按 Enter 键,则无法找出产生错误的方法
Can't figure out a way to produce an error if user hits Enter without giving an input
好的,所以我必须做一个计算每月数据账单的程序。我唯一卡住的是,如果用户单击enter而不输入任何内容,我无法让它给出错误。我尝试使用get line(),但我似乎不能让它读取字符。还有,我怎么能产生一个错误,因为我认为我做错了什么。
我也一直没有得到匹配的函数调用'getline'
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// State the different plans
cout << "A - $29.99 per month with 5000 megabytes.n";
cout << " $0.05 per additional megabyte, but onlyn";
cout << " $0.03 per additional megabyte if 50% orn";
cout << " more of the data was used on weekendsn";
cout << "B - $39.99 per month with 7500 megabytes.n";
cout << " $0.01 per additional megabyten";
cout << "C - $49.99 per month for unlimited megabytes.n";
// Ask what plan the customer bought
cout << "Enter A, B, or C to chose the plan the user has purchased: ";
char input;
getline(cin, input);
// Capitalize the input
input = toupper(input);
// Ignore anything after the first letter
cin.ignore(100, 'n');
使用std::getline()
最简单的方法是使其第二个参数为std::string
。
std::string input;
getline(cin, input);
if (input.size() == 0)
{
// Nothing was typed in before hitting Enter.
}
这比使用operator>>
简单得多,然后必须处理ignore()
和其他令人头疼的问题,等等…
我已经使用了cin。以下列方式获取:
char str [64];cin。getline (str, sizeof (str));
str将捕获在返回键之前输入的所有字符。如果用户直接点击return, str[0]将被设置为0,使str成为一个0长度的字符串,strlen(str)将为0。
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- C++数组队列实现方法错误
- 方法错误"not all control paths return a value"和方法不返回值
- OpenGL 顶点缓冲区类重定义和模板方法错误
- 如何在 VC++ 中通过引用传递另一个对象的方法(错误 C2664)
- 复数程序编译时的计算方法错误
- CMake 构建错误 - 虚拟方法错误缺少 vtable
- 接受 lambda 作为参数的类方法 - 错误消息
- c++程序方法错误visualstudio
- OpenCV "findContours"方法错误
- std::线程类方法错误
- 基类没有新方法错误
- C++派生类继承方法错误
- 指向类方法错误c++11的指针数组
- 使用jni调用方法:错误的jni oop参数
- QVector.push_back方法错误
- 对静态方法错误的未定义引用
- Friend方法错误
- async_write方法错误
- 重写方法错误C++