如何在C++中提取数字的数字?

Jon*_*ohn 0 c++

基本上我想制作一个小程序,当你输入一个数字(比如145)时,它会读取3位数并打印出最大的数字.

int a,b,c,max;

cout << "Enter a, b and c: ";
cin >> a >> b >> c;

max = a;
if (b>max)
    max = b;
if (c>max)
    max = c;
cout << "Max is " << max << "\n";
Run Code Online (Sandbox Code Playgroud)

我想到使用这样的东西,但我不知道如何让计算机读取每个数字.谢谢!

Kei*_*yne 5

int将第一行更改为char.

#include <iostream>

int main() {
  char a, b, c, max;

  std::cout << "Enter a, b and c: ";
  std::cin >> a >> b >> c;

  max = a;
  if (b>max)
    max = b;
  if (c>max)
    max = c;
  std::cout << "Max is " << max << "\n";

}
Run Code Online (Sandbox Code Playgroud)

这是有效的,但实际上不是解决这个问题的正确方法IMO for C++.

这稍微好一些,但没有任何输入验证:

#include <iostream>
#include <string>
#include <algorithm>

int main() {

  std::string s;

  std::cout << "Enter a number: ";
  std::cin >> s;

  char maxChar = *max_element(s.begin(), s.end());

  std::cout << "Max is " << maxChar << "\n";
}
Run Code Online (Sandbox Code Playgroud)