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

来源:互联网 发布:vmware 12 mac版下载 编辑:程序博客网 时间:2024/06/04 01:20

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

  • 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;}
原创粉丝点击