c++中的输入输出

c++中的输入输出

1,使用标准输入输出流(cin和cout):可以使用cin来从控制台输入数据,使用cout来向控制台输出数据。

1.1 对一个数的输入输出

#include <iostream>
using namespace std;

int main(){
	int n;
	// 输出一行字符串
	cout << "Please enter a number:\n";
	// 输入一个整数,并赋值给n
	cin >> n;
	// 输出n
	cout << n;
	return 0; 
}

1.2 输入n个数并把其存入数组中

#include <iostream>
using namespace std;

int main(){
	int n;
    cout << "Please enter the number of elements\n";
	cin >> n;
	int a[n];
	cout << "enter" << n <<"number\n";
	// 输入n个数 
	for(int i = 0;i<n;i++){
		cin >> a[i];
	}
	// 遍历数组 
	for(int i = 0;i<n;i++){
		cout << a[i];
	}    
	return 0; 
}

1.3 输入一行字符串

#include <iostream>
#include <string>
using namespace std;

int main() {
  string input;
  cout << "Enter a string: ";
  getline(cin, input);

  cout << "You entered: " << input;

  return 0;
}

2,使用文件输入输出流(ifstream和ofstream):可以使用ifstream来从文件中读取数据,使用ofstream来向文件中写入数据。

#include <fstream>
#include <iostream>

int main() {
  std::ofstream outfile("output.txt");
  outfile << "Hello, world!" << std::endl;
  outfile.close();

  std::ifstream infile("input.txt");
  std::string line;
  while (std::getline(infile, line)) {
    std::cout << line << std::endl;
  }
  infile.close();

  return 0;
}

3,使用字符串流(stringstream):可以使用stringstream来将数据转换为字符串,或者从字符串中提取数据。

#include <iostream>
#include <sstream>

int main() {
  std::stringstream ss;
  int number = 123;
  ss << "The number is: " << number;

  std::string result = ss.str();
  std::cout << result;

  return 0;
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值