2

例如:

int input;
cout << "Please enter how many burgers you'd like" << endl;
cin >> input;

什么是缩短“输入”并且只接受前两位数字的最简单方法。继续这个例子:

用户输入:432534。输入值:43。

用户输入:12342342341234123412341235450596459863045896045。输入值:12。

(编辑:说“数字”而不是“位”)

4

8 回答 8

5

我认为std::string运营可以让你回家。

std::string inputstr;
cout << "Please enter how many burgers you'd like" << endl;
cin >> inputstr;
inputstr = inputstr.substr(0, 2);

int input    
input = std::stoi(inputstr);      // C++11
input = atoi(inputstr.cstr());    // pre-C++11

文档: http:
//en.cppreference.com/w/cpp/string/basic_string/stol
http://en.cppreference.com/w/cpp/string/byte/atoi

于 2013-10-15T16:09:05.047 回答
3

读取前两位数字并形成一个整数:

int digit1 = std::cin.get() - '0';
int digit2 = std::cin.get() - '0';
int input = digit1 * 10 + digit2;

然后丢弃其余的输入:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

要处理负号,您可以执行以下操作:

int input = 1;

int digit1 = std::cin.get();
if (digit1 == '-') {
    input = -1;
    digit1 = std::cin.get();
}

digit1 -= '0';
int digit2 = std::cin.get() - '0';
input *= (digit1 * 10) + digit2;

如下所述,如果用户输入除了两个数字作为前两个字符之外的任何内容,这将不起作用。这很容易通过阅读和使用std::isdigit测试来检查。继续前进或抛出某种错误取决于您。

如果用户只输入一位数字,这也不起作用。如果您也需要它,您可以读取整个字符串并使用它的大小或检查 EOF。

输入操作本身也没有错误检查,但应该有真实代码。

于 2013-10-15T15:59:52.327 回答
1

我很惊讶没有人提到fscanf。虽然 C++ 纯粹主义者可能会反对,但与这种情况相比,这需要更少的代码(以及更好的错误检查)cin

int res = 0;
std::cout << "Please enter how many burgers you'd like" << std::endl;
if (fscanf(stdin, "%02d", &res) != 1) {
    std::cerr << "Invalid Input" << std::endl;
}
int c;
do {
    c = fgetc(stdin);
} while (c != '\n' && c != EOF);
std::cout << "Got " << res << std::endl;
于 2013-10-15T16:39:31.497 回答
0

input为字符串并将第一个两个字符转换为int

#include <sstream>
#include <string>
#include<iostream>

int main()
{
   std::string input ;

   std::cin>>input;
   std::stringstream iss(input.substr(0,2));
   int num;

   iss >> num;

   std::cout<<num;

}
于 2013-10-15T16:06:19.537 回答
0
int i;
cin >> i;
while (i >= 100 || i <= -100) {
   i = i / 10;  // remove and ignore the last digit
}

由于整数溢出,这不适用于非常大的数字。我只是把它作为一个非常简单的算法包括在内。

于 2013-10-15T16:10:40.237 回答
0

读取一个字符串并提取前 2 个字符:

std::string input;
cout << "Please enter how many burgers you'd like" << endl;
cin >> input;
int first2;
if (input.size()>=1)
{
    if (input[0] == '-')
       std::cerr << "Negative num of burgers";
    else
       first2 = atoi(input.substr(0,2).c_str());
}
else
    std::cout << "Null number";
于 2013-10-15T16:14:43.143 回答
0

我认为这种方法很容易理解。

int input;
cout << "Please enter how many burgers you'd like" << endl;
cin >> input;

char cTemp[50];

itoa(input, cTemp, 10);

char cResult[3] = {cTemp[0], cTemp[1], '\0'};

int output = atoi(cResult);
于 2013-10-15T16:16:22.190 回答
-3

让我通过为您重写来回答这个问题:

如何从标准输入读取字符串并将前 2 个字符写入标准输出?

于 2013-10-15T16:11:47.973 回答