21xrx.com
2025-03-21 20:05:12 Friday
文章检索 我的文章 写文章
C++如何输入两个数?
2023-07-07 15:17:00 深夜i     11     0
C++ 输入 两个数

C++作为一门高级编程语言,提供了很多输入的方法。要输入两个数,可以使用以下三种方法。

方法一:使用cin输入流

cin是一个输入流,可以读取标准输入的值。要输入两个数,可以使用cin流读取键盘输入的两个值,并将它们存储在两个变量中。下面是一个简单的示例代码:

#include <iostream>
using namespace std;
int main() b;
  cout << "Please enter two numbers: ";
  cin >> a >> b;
  cout << "The numbers you entered are: " << a << " and " << b << endl;
  return 0;

在上述代码中,我们首先声明了两个变量a和b,它们都是整数类型。然后将一个友好的提示信息输出给用户,要求用户输入两个数。接着,通过cin流从标准输入流中获取这两个数,并将它们存储在变量a和b中。最后,打印输出这两个数的值。

方法二:使用scanf函数

scanf是C语言的标准库函数,C++中也可以使用。与cin不同的是,scanf函数使用格式化字符串指定读取数据的类型。下面的示例代码演示了如何使用scanf函数输入两个整数:

#include <cstdio>
int main() {
  int a, b;
  printf("Please enter two numbers: ");
  scanf("%d %d", &a, &b);
  printf("The numbers you entered are: %d and %d\n", a, b);
  return 0;
}

需要注意的是,scanf函数需要使用指针来传递变量的地址。

方法三:使用getline函数

getline函数可以一次性读取一行字符串,并将其保存在一个string对象中。我们可以根据需要,将这个字符串分解成多个数字或其他类型的数据。下面是一个示例代码,演示如何使用getline函数输入两个整数:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string input;
  int a, b;
  cout << "Please enter two numbers: ";
  getline(cin, input);
  sscanf(input.c_str(), "%d %d", &a, &b);
  cout << "The numbers you entered are: " << a << " and " << b << endl;
  return 0;
}

在上述代码中,我们先使用getline函数读取一行输入的字符串,然后使用sscanf函数将这个字符串转换成两个整数,最后输出这两个整数。需要注意的是,sscanf函数需要使用字符串的c_str函数获得字符串的首地址。

  
  

评论区