1 eatwhite
2 get
3 getline
4 gcount
5 ignore
6 operator>>
7 peek
8 read
9 seekg
10 tellg
1 eatwhite
忽略前导空格
2 gcount
统计最后输入的字符个数
3 get
从流中提取字符,包括空格
std::cin.get(ch);//等价于ch=std::cin.get;
1 #include <iostream> 2 3 void main() 4 { 5 char ch = 0; 6 7 while (ch != ' ') 8 { 9 std::cout.put(ch); 10 std::cin.get(ch);//等价于ch=std::cin.get; 11 } 12 13 system("pause"); 14 }
面试,复合表达式
1 #include <iostream> 2 3 void main() 4 { 5 char ch = 0; 6 7 while ((ch = std::cin.get()) != ' ')//复合表达式 8 { 9 std::cout.put(ch); 10 } 11 12 system("pause"); 13 }
std::cin.get(buf, 80, 'x');//提取一段文本,最大长度为80,遇到'x'结束
1 #include <iostream> 2 3 void main() 4 { 5 char buf[80]; 6 7 std::cin.get(buf, 80, 'x');//提取一段文本,最大长度为80,遇到'x'结束 8 9 std::cout << buf << std::endl; 10 11 system("pause"); 12 }
4 getline
从流中提取一行字符
std::cin.getline(str, 10);//限定长度,保存10-1=9个字符,最后一个字符是' ',作用:限制输入密码的长度,防止缓冲区溢出
1 #include <iostream> 2 3 void main() 4 { 5 char str[30] = { 0 }; 6 7 std::cin.getline(str, 10);//限定长度,保存10-1=9个字符,最后一个字符是' ',作用:限制输入密码的长度,防止缓冲区溢出 8 9 std::cout << str; 10 11 system("pause"); 12 }
按行读取文件
1 #include <iostream> 2 #include <fstream> 3 4 void main() 5 { 6 std::ifstream fin("F:\1.txt");//创建读取文件流 7 8 for (int i = 0; i < 4; i++) 9 { 10 char str[100] = { 0 }; 11 fin.getline(str, 100);//从流中提取一行字符 12 std::cout << str << std::endl;//打印 13 } 14 15 fin.close();//关闭文件 16 17 system("pause"); 18 }
std::cin.getline(buf, 80, 'x');//逐行读取,以'x'为结束
可以反复读取,适合提取数据,以'x'作为间隔
1 #include <iostream> 2 3 void main() 4 { 5 char buf[80]; 6 7 std::cin.getline(buf, 80, 'x');//逐行读取,以'x'为结束 8 std::cout << buf << std::endl; 9 10 std::cin.getline(buf, 80, 'x');//逐行读取,以'x'为结束 11 std::cout << buf << std::endl; 12 13 system("pause"); 14 }
5 ignore
提取并丢弃流中指定字符
6 operator>>
提取运算符
7 peek
返回流中下一个字符,但不从流中删除
8 read
无格式输入字节数
9 seekg
移动输入流指针
10 tellg
返回输入流中指定位置的指针值