c++之标准库类型相关题目

标准库类型相关课后习题练习

  • Q:1. 编写一个程序,从string对象中去掉标点符号。要求输入程序的字符串必须包含标点符号,输出结果则是去掉标点符号后的string对象。
#include<iostream>
#include<string>
using namespace std;

int main()

{
    string s, result_str;
    bool has_punct = false;//用于标记字符串中有无标点
    char ch;
    //输入字符串
    cout << "Enter a string:" << endl;
    getline(cin, s);
    //处理字符串:去掉其中的标点
    for  (string::size_type  index  =  0;  index  !=  s.size();  ++index)
    {
        ch = s[index];
        if (ispunct(ch))     //ispunct(ch) 如果ch是标点符号,则为true。
            has_punct = true;
        else 
            result_str += ch;
    }
    if (has_punct)
        cout << "Result:" << endl << result_str <<endl;
    else {
        cout << "No punctuation character in the string?!" << 
            endl;
        return -1;
    }

    return 0;
}
  • Q:2. 读一组整数到vector对象,头尾两两相加,计算每对元素的和,并输出,多余的加以提示。
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> ivec;
    int ival;
    //  读入数据到 vector  对象
    cout << "Enter numbers(Ctrl+Z to end):" << endl;
    while (cin>>ival)
        ivec.push_back(ival);
    //  计算相邻元素的和并输出
    if (ivec.size() == 0) {
        cout << "No element?!" << endl;
        return -1;
    }
    cout << "Sum of each pair of adjacent elements in the vector:"
        << endl;
    for (vector<int>::size_type ix = 0; ix < (ivec.size())/2;++ix)
    {
        cout << ivec[ix] + ivec[ivec.size()-ix-1] << "\t";
    }
    if (ivec.size() % 2 != 0) //  提示最后一个元素没有求和
        cout << endl
        << "The last element is not been summed "
        << "and its value is "
        << ivec[(ivec.size())/2] << endl;
    return 0;
}
  • Q :3. 读入一段文本到vector对象,每个单词存储为vector中的一个元素。其中将其转化为大写。输出vector对象中转化后的元素,每八个为一行输出。
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main()
{
    vector<string> words;
    string ch;
    cout<< "Enter words: "<< endl;
    while(cin >> ch)
        words.push_back(ch);
    if(words.size() == 0)
    {
        cout << "NO element!"<< endl;
        return -1;
    }
    cout << "Translate element: "<< endl;
        //对每个单词进行转化为大写
    for(vector<string>::size_type index = 0; index != words.size(); ++index)
    {
        for(string::size_type ix = 0; ix != words[index].size(); ++ix)
            words[index][ix] = toupper(words[index][ix]);
        cout << words[index]<< " ";
        //每八个一行输出
        if((index+1)%8 == 0)
            cout << endl;
    }
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wcyd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值