程序读取输入数据

这篇博客介绍了C++中读取不同格式输入数据的方法,包括读取日期时间、以字符串形式合并所有输入以及处理行内未知数量的数据。示例代码展示了如何使用scanf和getline函数,以及如何利用istringstream处理 vector 和二维数组来读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序读取输入数据

c++

读取日期时间

#include <iostream>

using namespace std;

int main() {
    
    int year, month, day, hour, minute, second;
    scanf("%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
    
    printf("%d %d %d %d %d %d", year, month, day, hour, minute, second);
    
    return 0;
}
/*
2021-02-21 01:02:03
*/

以字符串形式读取所有输入

#include <iostream>

using namespace std;

int main() {
    
    string s;
    while (true) {
        string line;
        if (!getline(cin, line)) break;
        s += line + "\n";
    }
    
    cout << s << endl;
    
    return 0;
}
/*
#include <iostream>

using namespace std;

int main() {

    cout << "hello world" << endl;

    return 0;
}
*/

读取一行未知个数的数据

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

int main() {
    
    string line;
    getline(cin, line);
    stringstream ssin(line);
    
    vector<int> res;
    int x;
    while (ssin >> x) res.push_back(x);
    
    for (auto x : res) cout << x << ' ';
    cout << endl;
    
    return 0;
}
/*
1 2 3 4 5
*/

读取行数列数未知的数据

#include <iostream>
#include <sstream>

using namespace std;

const int N = 1010;

int n, m;
int g[N][N];

int main() {
    
    string line;
    while (getline(cin, line)) {
        n++, m = 0;
        stringstream ssin(line);
        int x;
        while (ssin >> x) g[n][++m] = x;
    }
    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++)
            cout << g[i][j] << ' ';
        cout << endl;
    }
    
    return 0;
}
/*
1 2 3
4 5 6
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值