Contents

C++读写方法

C++ 读写方法

输入输出流 Iostream

标准输入流

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 输入n个数字
// 输入n个数字
for (int i = 0; i < n; i++)cin >> nums[i];
// 输入未知个数的数字
int i = 0;
while (cin >> n) {
    nums[i] = n;
    nums[i] = n;
}
// 提取输入中的数字
// 提取输入中的坐标(0,0),(1,1)
char c;
int x0, y0, x1, y1;
cin >> c >> x0 >> c >> y0 >> c >> c >> c >> x1 >> c >> y1 >> c;

Cout 格式化输出

1
2
3
4
5
6
#include <iomanip>
cout << hex << 10 << endl;  // 输出16进制
cout << oct << 8 << endl;   // 输出8进制
cout << setprecision(4) << 1.11111111;  // 设置输出精度
cout << setw(6) << right << 10; // 输出指定宽度\右(左)对齐
cout << year << '-' << setw(2) << setfill('0') << month << '-' << std::setw(2) << std::setfill('0') << day << endl; // 输出年月日

字符串

主要的表示方法有以下四种:

  • string 需要引入头文件
  • char * 指向字符串的指针,实质上是指向字符串的首字母
  • const char* 指向一个常量类型的字符类型(不可修改
  • char[] 字符数组,对应一个字符串

字符串读取

1
2
3
4
cin >> s;   //不能读入空格,以空格,制表符,回车为结束标志
string str;
getline(cin, str); //可以读入空格和制表符,以回车作为结束标志,要注意getline的尾部是有一个回车的
getline(cin, str, ' '); // 表示以' '作为结束

常见操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
str.at(index);
str[index]; // 从string中获取char字符
string str1 = "this is a testing string.";
string str2 = "n example";
// 函数
str1.replace(9, 5, str2); // 第9个字符开始5个字符被str2代替, this is an example string
str.erase(10, 8);    //擦除第10个字符开始的8个字符
str.insert(6, str2); //在第6个位置插入str2

// 比较
if (str1 < str2) cout << "hey";
if (str1.compare(str2) < 0) cout << "hey";
// 连接两个string串
string str0 = str1 + str2;
str0 = str1.append(str2);
str.size();  //长度
// 查找
str = "abcabc";
str.find("ab"); //找到第一个 0
str.find("ab", 2);    //找到第二个 4
str.rfind("ab", 2);   // 0
string s2 = str.substr(0, 5);   // 从0开始取5个字符

//转换
str = "123";
int i = std::stoi(str);
long l = std::stol(str);
float f = std::stof(str);
double d = std::stof(str);