C++复合数据类型:字符数组|读取键盘输入|简单读写文件

字符数组(C风格字符串)

字符串就是一串字符的集合,本质上其实是一个“字符的数组”。
在C中为了区分“字符数组”和“字符串”,C语言规定字符串必须用空字符结束,作为标记。
例如:

char str1[5] = {'h', 'e', 'l', 'l', 'o'}; // 不是字符串,是字符数组
char str2[6] = {'h', 'e', 'l', 'l', 'o', '\0'}; // 字符串

但是这样不方便,因此定义字符串是用双引号

char str3[] = "hello"; // 要不不指定,指定长度5的话会报错,因为最后有一个空字符
cout << sizeof(str3) << endl; //输出是6

建议使用标准库string,少使用C语言的字符数组类型。

读取键盘输入

使用输入操作符读取单词

标准库中提供了iostream,可以使用内置的cin对象,
特点:忽略开始的空白字符,遇到下一个空白字符就会停止(空格,回车,制表符等),如果输入“hello world”,读取到的就只有hello。注意"world"并没有丢,只是保存在输入流的“输入队列中”,可以使用更多string 对象获取。

string str;
// 读取键盘输入,遇到空白字符停止
cin >> str; //输入:hello world
cout << str << endl; //输出:hello

string str1, str2;
cin >> str1 >> str2;  // 输入:hello world
cout << str1 << str2 << endl; //输出:helloworld
//或者可以分开获取
string str3, str4;
cin >> str3; //输入:hello world
cout << str3 << endl; //输出:hello
cin >> str4;
cout << str4 << endl; //输出world

读取一行信息getline

getline函数有两个参数,一个是输入流对象cin, 一个是保存字符串的string对象,他会一直读取输入流中的内容,知道遇到换行符为止,然后把所有的内容保存到string对象中。

string str
getline(cin, str);
cout << str << endl;

使用get读取一个字符

char ch;
ch = cin.get(); //只能获取第一个字符
//或者
cin.get(ch)

char str[20];
cin.get(str, 20); //字符数组
cout << str << endl;

读写文件

C++中提供ifstream 和 ofstream类分别用于文件输入和输出,需要引入头文件fstream。

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
	ifstream input("./test.txt"); //读入指的是入计算机
	ofstream output("./output.txt"); 

    //1.按照单词逐个读取
    // string word;
    // while(input >> word)
    // {
    //     cout << word << endl;
    // }
    //读取结束后指针在文件的最后,直接运行下面代码会没有输出,需要将上面的注释掉

    //2.逐行读取
    // string line;
    // while(getline(input, line))
    // {
    //     cout << line << endl;
    // }

    //3.逐个字符读取
    char ch;
    while(input.get(ch))
    {
        cout << ch << endl;
    }

	//逐个字符写入
	char ch;
	while(input.get(ch))
	{
		output << ch << endl;
	}
}
  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值