有没有更好的办法?新的c ++

时间:2016-12-26 16:23:25

标签: c++

我是c ++的新手,但对编码有基本的了解。这个程序工作得很好,但我想知道是否有更好的方法来做到这一点。

该程序通过获取姓氏的前三个字母和名字的前两个字母来制作星球大战的名称,以制作星球大战名称的第一个名称。然后,对于你的星球大战姓氏,你需要母亲姓氏的前两个字母以及你出生的城市的前三个字母。

// starWarsName.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string> 
using namespace std;


int main()
{
    string firstName; 
    string surname; 
    string maidenName;
    string city;
    cout << "This program is designed to make you a star wars name, it takes some information and concatinates parts of the information to make your NEW name" <<endl << endl;

    cout << "please enter your first name" << endl;
    cin >> firstName;
    cout << "please enter your surname" <<endl;
    cin >> surname; 
    cout << "what is your mothers maiden name?" << endl;
    cin >> maidenName;
    cout << "please tel me which city you were born in" << endl;
    cin >> city; 

    cout << firstName << " " << surname << endl;
    cout << firstName[0] << " " << surname << endl;

    int size = firstName.length();
    //cout << size;
    cout << surname[0] << surname[1] << surname[2] << firstName[0] << firstName[1];
    cout << " " << maidenName[0] << maidenName[1] << city[0] << city[1] << city[2];

    cin.get();
    cin.ignore();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您可以在此处使用 string :: substr 来存储字符序列,而不是一次又一次地写姓氏[0] ..姓[2]。

以下是 string :: substr

的示例
#include <iostream>
#include <string>

int main ()
{
std::string str="We think in generalities, but we live in details.";
                                       // (quoting Alfred N. Whitehead)

std::string str2 = str.substr (3,5);     // "think"

std::size_t pos = str.find("live");      // position of "live" in str

std::string str3 = str.substr (pos);     // get from "live" to the end

std::cout << str2 << ' ' << str3 << '\n';

return 0;
}

输出:

think live in details.
相关问题