如果用户在没有输入的情况下按 Enter 键,则无法找出产生错误的方法

Can't figure out a way to produce an error if user hits Enter without giving an input

本文关键字:方法 错误 用户 输入 Enter 情况下 如果      更新时间:2023-10-16

好的,所以我必须做一个计算每月数据账单的程序。我唯一卡住的是,如果用户单击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。