c++ I/O流的注意事项——输入数字以逗号间隔/常规输入

逗号一行型

1.当输入以逗号连接时,例如 输入或者输入1,32,15,17(中间有空格) 因为c++的空格可以直接ignore,把“,”当成一个char,然后交错cin.get()进行使用,注意:cin.get()每次都读了一个字符,cin.get()和直接cin的区别是:cin.get()中的cin就是读取的一个对象将其识别为一个字符,空格与换行都可以识别。执行效果如下:

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <map>
#include <string>
#include <memory>
#include <vector>

int main() {
    int temp;
    vector<int>res;
    char a;
    while(1) {
        cin >> temp;
        res.push_back(temp);
        if (cin.get() == '\n') break;
    }
    for (auto p : res) cout << p << "   ";
    system("pause");
    return 0;
}

实验效果图如下所示:


图片.png

逗号带空格一行型

和上述区别就是逗号和逗号中间带了一个(或若干个空格):
1, 2, 23, 45
代码同第一个代码:

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <map>
#include <string>
#include <memory>
#include <vector>

int main() {
    int temp;
    vector<int>res;
    char a;
    while(1) {
        cin >> temp;                    //cin>> 不会对回车和空格进行识别,因而不管一个int前面有多少个空格都不需要care
        res.push_back(temp);
        if (cin.get() == '\n') break;   //这一步执行cin.get()后读入逗号或末置位回车
    }
    for (auto p : res) cout << p << "   ";
    system("pause");
    return 0;
}

执行结果如图所示:


图片.png

2.数字k+k行型

3.常规输入:
输入格式:
2
2
1 2
3
0 2 3
第一行 为几个数列,第二行第三行为第一数列元素的数目和各元素的值,依次类推;

    int n;
    cin >> n;
    vector<vector<int>> a;
    for (int i = 0; i < n; i++) {
        int length;
        cin >> length;
        vector<int> tmp;
        int cycle = 1;
        int temp;
        while (cycle) {
            cin >> temp;
            tmp.push_back(temp);
            if (cin.get() == '\n') { //这个cin.get()可以读入换行符或者空格符
                cycle = 0;
            }
        }
        a.push_back(tmp);
        tmp.clear();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。