在数字中的特定数字处查找数字

时间:2015-07-24 14:40:08

标签: c++ c++11 numbers integer digits

我希望在特定索引处显示数字。

假设数字为" 123456789"我需要从左边返回位置3的数字。

我应该将此数字转换为字符串并将特定索引处的字符重新转换为整数以获取数字值吗?

在C ++中是否有任何内置函数?

3 个答案:

答案 0 :(得分:5)

要获取数字中任何位置的数字,您可以使用简单的字符串转换:

int foo = 123456789;
int pos = 3;
// convert to string and use the [] operator
std::cout << std::to_string(foo)[pos - 1];//need to subtract 1 as C++ is 0 index based

答案 1 :(得分:1)

这应该返回数字的第三个数字!

cout << "Enter an integer";
int number;
cin >> number;
int n = number / 100 % 10

或(对于所有数字):

 int number = 12345;
 int numSize = 5;
for (int i=numSize-1; i>=0; i--) {
  int y = pow(10, i);
  int z = number/y;
  int x2 = number / (y * 10);
  printf("%d-",z - x2*10 );
}

答案 2 :(得分:1)

使用std :: stringstream

std::string showMSD3(int foo)
{
   std::stringstream ssOut;

   std::string sign;
   std::stringstream ss1;
   if(foo < 0) {
      ss1 << (-1 * foo);
      sign = '-';
   }
   else
      ss1 << foo;

   std::string s = ss1.str();

   ssOut << "               foo string: '"
         << sign << s << "'" << std::endl;

   if(s.size() > 2)
   {
      ssOut << " Most Significant Digit 3: "
            << s[2] // 1st digit at offsset 0
            << "\n            has hex value: 0x"
            << std::setw(2) << std::setfill('0') << std::hex
            << (s[2] - '0')
            << std::endl;
   }
   else
      ssOut << "                      Err: foo has only "
            << s.size() << " digits" << std::endl;

   return (ssOut.str());
}

和更接近主要地方(可能在主要地方):

   // test 1
   {
      std::cout << showMSD3(123456789) << std::endl;
   }

   // test 2
   {
      std::cout << showMSD3(12) << std::endl;
   }

   // test 3 - handle negative integer
   {
      std::cout << showMSD3(-123) << std::endl;
   }

带输出

               foo string: '123456789'
 Most Significant Digit 3: 3
            has hex value: 0x03

               foo string: '12'
                      Err: foo has only 2 digits

               foo string: '-123'
 Most Significant Digit 3: 3
            has hex value: 0x03