C++ 输入输出的格式问题

C++ 输入输出的格式问题

示例1:

输入一行整数,每个整数之间用一个或多个空格隔开,输入回车结束输入。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec;

    do {
        int num = 0;
        cin >> num;
        vec.push_back(num);
    } while(cin.get() != '\n');

    for(auto num : vec) {
        cout << num << endl;
    }

    return 0;
}

示例2:

输入一行字符串,字符串中可以用空格,输入回车结束输入。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;

    getline(cin, str);

    cout << str << endl;

    return 0;
}

示例3

输入字符串,各字符串之间以空格隔开,以回车结束输入

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
    vector<string> vec;
    do {
        string str;
        cin >> str;
        vec.push_back(str);
    } while(cin.get() != '\n');

    for(auto str : vec) {
        cout << str << endl;
    }

    return 0;
}

示例4

给定一个字符串,提取其中的“单词”

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    string str;
    getline(cin, str);

    int h1 = 0, h2 = 0;
    vector<string> vec;
    do {
        while(h1 < str.size() && str[h1] == ' ') h1++;
        h2 = h1;
        while(h2 < str.size() && str[h2] != ' ') h2++;
        string tmp(str.begin()+h1, str.begin()+h2);
        vec.push_back(tmp);
        h1 = h2;
    } while(h1 < str.size());

    for(auto str : vec) {
        cout << str << endl;
    }

    return 0;
}
vector<string> vec;
string str;
while(cin >> str) {
    vec.push_back(str);
}

示例5

将一串数字输出,数字之间有空格,开头和结尾没有空格

    /*
    for(int i = 0;i < res.size();i++) {
        i < res.size()-1 ? cout << res[i] << " " : cout << res[i];
    }
    */
    for(int i = 0;i < res.size();i++) {
        cout << res[i];
        i < res.size()-1 && cout << " ";
    }
    for(int i = 0;i < 6;i++) {
        cout << a[i];
        i == 5 ? cout << endl : cout << ' ';
    }

    for(int i = 0;i < vec.size();i++) {
        cout << vec[i];
        i == vec.size()-1 ? cout << endl : cout << ' ';
    }

示例6

以EOF结尾,即文件结束符。
这种处理方式适用于以文件作为输入,或者在键盘手动输入文件结束符作为结尾标记。

int n;
while(cin>>n)
{
    //处理输入的合法值。
}

在windows上输入EOF的方法为Ctrl+Z
其它平台上输入EOF的方法为Ctrl+D

示例7

将栈中的元素从栈顶到栈底依次输出,中间有空格,结尾是换行。

链接:https://www.nowcoder.com/questionTerminal/ee5de2e7c45a46a090c1ced2fdc62355?toCommentId=1593971
来源:牛客网

    while(!st.empty()) {
        cout << st.top();
        st.pop();
        st.empty() ? cout << endl : cout << ' ';
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值