《C++ Primer Plus》学习笔记——第5章 循环和文本输入

1 概述

C++中支持三种循环,for循环、while循环和do while循环。

2 for循环

for循环遍历字符串输出

int main() {
    using namespace std;
    string str;
    cin >> str;
    for (int i = 0; i < str.size(); ++i) {
        cout << "str[" << i <<"] = " << str[i] << endl;
    }
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

输出

234fds
str[0] = 2
str[1] = 3
str[2] = 4
str[3] = f
str[4] = d
str[5] = s
Hello, World!

这里的++i通常也有人写常i++,有前缀和后缀的区别。从语义上来说,二者都是对i进行自增。但是从效率上来说,可能存在差异。通常i++会将i复制一个副本,然后加一,然后再写回,而++i则是直接在i上面加一写回,效率要高一些。但是通常编译器优化时会将基本数据类型中的i++转换成++i。而对于类而言,用户自定义的自增函数,则++i类似的会更高效一些。

2 while循环

int main() {
    using namespace std;
    string str;
    cin >> str;
    int i = 0;
    while(i < str.size()) {
        cout << "str[" << i <<"] = " << str[i++] << endl;
    }
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

输出

234fds
str[0] = 2
str[1] = 3
str[2] = 4
str[3] = f
str[4] = d
str[5] = s

只要while判断为true则执行循环体内容

3 do while循环

int main() {
    using namespace std;
    string str;
    cin >> str;
    int i = 0;
    do {
        cout << "str[" << i <<"] = " << str[i++] << endl;
    }while(i < str.size());243
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

输出

234fds
str[0] = 2
str[1] = 3
str[2] = 4
str[3] = f
str[4] = d
str[5] = s

4 循环和文本输入

4.1 空格等输入问题

#include <iostream>

int main() {
    using namespace std;
    char ch;
    int count = 0;
    cout << "enter characters; enter # to quit:\n";
    cin >> ch;
    while (ch != '#') {
        cout << ch;
        ++count;
        cin >> ch;
    }
    cout << endl << count << " characters read\n";
    return 0;
}

输出

enter characters; enter # to quit:
see ken run#really fast
seekenrun
9 characters read

其中空格被忽略了,这是因为cin读取基本类型时会忽略空格和换行符,因为空格没有被回显,也没有被计入个数中。同时cin会有缓冲区的存在,当输入一系列字符后,并不会输入一个就发送给程序,而是放到了cin的缓冲区中,当输入enter时,缓冲区中的数据才被发送给程序。
如果想保留空格,制表符,换行符的输入,可以使用cin中的get函数

#include <iostream>

int main() {
    using namespace std;
    char ch;
    int count = 0;
    cout << "enter characters; enter # to quit:\n";
    cin.get(ch);
    while (ch != '#') {
        cout << ch;
        ++count;
        cin.get(ch);
    }
    cout << endl << count << " characters read\n";
    return 0;
}

输出

enter characters; enter # to quit:
Did you use a #a pencil?
Did you use a 
14 characters read

4.2 文件尾条件

如果输入来自于文件,可以使用检测文件尾(EOF)的技术来判断是否到达了文件的末尾。
常见的字符输入做法

cin.get(ch);
while (!cin.fail()) {
	...
	cin.get(ch);
}

可简化为

while (cin.get(ch) {
	...
}

cin.get返回cin对象,istream中提供了一个将其对象转换成bool值的函数,这里会自动调用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值