截断除前两个数字之外的整数的所有数字

Truncate all digits of an integer except the first two

本文关键字:数字 整数 两个      更新时间:2023-10-16

例如:

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

缩短"输入"并仅接受前两位数字的最简单方法是什么。要继续该示例,请执行以下操作:

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

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

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

我认为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/stolhttp://en.cppreference.com/w/cpp/string/byte/atoi

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

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。

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

我很

惊讶没有人提到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;
int i;
cin >> i;
while (i >= 100 || i <= -100) {
   i = i / 10;  // remove and ignore the last digit
}

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

读取一个字符串并提取前 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";

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;
}

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

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], ''};
int output = atoi(cResult);

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

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