注册 登录
编程论坛 C++教室

添加串类问题

醉了浮生 发布于 2011-11-11 16:59, 467 次点击
/*编制一个程序,将字符串string2的后n个字符添加到字符串string1的末尾,并以'\0'结束。
具体要求:
(1)、字符串string1,string2,添加字符个数n皆由键盘输入。
(2)、字符串采用顺序存储结构,定义如下:
typedef struct sqstring
{ char data[MaxSize];
int length;
}SqString;
(3)、要求程序运行结果正确,键盘输入n值需讨论其的合法性,输出结果的提示信息描述完备、清晰。
思考:
(1)、能否采用字符指针的形式存储字符串?为什么?
(2)、如果要求将字符串string2的头n个字符添加到字符串string1的末尾,程序做何修改?
*/

#include <iostream>
using namespace std;

#define MaxSize 100

typedef struct sqstring
{
    char data[MaxSize];
    int length;
}SqString;

void StrAssign(SqString &s, char cstr[], int n)
{
    int i;
    for(i = 0; i < n; i++)
        s.data[i] = cstr[i];
    s.length = n;
}

void DispString(SqString s)
{
    int i;
    if(s.length > 0)
    {
        for(i = 0; i < s.length; i++)
            cout<<s.data[i];
        cout<<endl;
    }
}

int StrLength(SqString s)
{
    return s.length;
}

void StrAdd(SqString &s, SqString t, int n)
{
    int i, p;
    do
    {
        cout<<"输入错误,请重新输入!"<<endl;
        cin>>n;
    }while(n<0||n>t.length);
        p = s.length;
        for(i = 0; i < n; i++)
        {
            s.length++;
            s.data[p + i] = t.data[t.length - n + i];        
        }   
}

void main()
{
    int  p, q, i, j, s;
    char a[100], b[100];
    SqString string1, string2;
    cout << "请输入字符串string1的长度p = ";
    cin>>p;
    for(i = 0; i < p; i++)
    {
        cin>>a[i];
    }
    StrAssign(string1, a, p);
    cout<<"串string1为:";
    DispString(string1);
    cout << "请输入字符串string2的长度q = ";
    cin>>q;
    for(j = 0; j < q; j++)
    {
        cin>>b[j];
    }
    StrAssign(string2, b, q);
    cout<<"串string2为:";
    DispString(string2);
    cout<<"将字符串string2的后s个字符添加到字符串string1的末尾,请输入s = ";//为什么此处无论输入什么,输出结果都是输入错误
    cin>>s;
    StrAdd(string1, string2, s);
    DispString(string1);
}
//呜呜,求指点
0 回复
1