istream类的公有成员函数

时间:2023-03-09 09:12:17
istream类的公有成员函数

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;

 #include <iostream>

 void main()
{
char ch = ; while (ch != '\t')
{
std::cout.put(ch);
std::cin.get(ch);//等价于ch=std::cin.get;
} system("pause");
}

面试,复合表达式

 #include <iostream>

 void main()
{
char ch = ; while ((ch = std::cin.get()) != '\t')//复合表达式
{
std::cout.put(ch);
} system("pause");
}

std::cin.get(buf, 80, 'x');//提取一段文本,最大长度为80,遇到'x'结束

 #include <iostream>

 void main()
{
char buf[]; std::cin.get(buf, , 'x');//提取一段文本,最大长度为80,遇到'x'结束 std::cout << buf << std::endl; system("pause");
}

4 getline

从流中提取一行字符

std::cin.getline(str, 10);//限定长度,保存10-1=9个字符,最后一个字符是'\0',作用:限制输入密码的长度,防止缓冲区溢出

 #include <iostream>

 void main()
{
char str[] = { }; std::cin.getline(str, );//限定长度,保存10-1=9个字符,最后一个字符是'\0',作用:限制输入密码的长度,防止缓冲区溢出 std::cout << str; system("pause");
}

按行读取文件

 #include <iostream>
#include <fstream> void main()
{
std::ifstream fin("F:\\1.txt");//创建读取文件流 for (int i = ; i < ; i++)
{
char str[] = { };
fin.getline(str, );//从流中提取一行字符
std::cout << str << std::endl;//打印
} fin.close();//关闭文件 system("pause");
}

std::cin.getline(buf, 80, 'x');//逐行读取,以'x'为结束

可以反复读取,适合提取数据,以'x'作为间隔

 #include <iostream>

 void main()
{
char buf[]; std::cin.getline(buf, , 'x');//逐行读取,以'x'为结束
std::cout << buf << std::endl; std::cin.getline(buf, , 'x');//逐行读取,以'x'为结束
std::cout << buf << std::endl; system("pause");
}

5 ignore

提取并丢弃流中指定字符

6 operator>>

提取运算符

7 peek

返回流中下一个字符,但不从流中删除

8 read

无格式输入字节数

9 seekg

移动输入流指针

10 tellg

返回输入流中指定位置的指针值