静态数组实现求子串--作业0401--实验三(串)

来源:互联网 发布:php exec java 不执行 编辑:程序博客网 时间:2024/06/13 21:39
获取子串时,输入空格就会有乱码,倒腾半天才知道接受母串时出错,cin.get(S,MAX_STRLEN); 不能接受空格回车之类的,gets()可以实现。小问题,害的自己狂晕。还是基础不行啊。
  1.  用静态数组实现求子串(SubString)操作。从屏幕输入:
      主串"Life is like a box of chocolate!"
      子串的位置
      子串长度
     输出子串"a box of chocolate!"。
    #include <stdio.h>
  2. #include <iostream.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #define MAX_STRLEN 255
  6. typedef char SString[MAX_STRLEN+1];
  7. int SubString (SString &Sub,SString S,int pos,int len)
  8. {
  9.     if (pos<1||pos>S[0]||len<0||len>S[0]-pos+1)
  10.     {
  11.         cout<<"Error"<<endl;
  12.         return 0;
  13.     }
  14.     for (int i=1;i<=len;i++)
  15.     {
  16.         Sub[i]=S[pos+i-1];
  17.     }
  18.     Sub[0]=len;
  19.     Sub[i]='/0';    
  20.     return 1;
  21. int main()
  22. {
  23.    char Sub[MAX_STRLEN+1];
  24.    int pos,len;
  25.    char S[MAX_STRLEN+1];
  26.    for (int i=0;i<MAX_STRLEN;i++)
  27.    {
  28.    cout<<"SubString.cpp/n=============/n/n"<<endl;
  29.    cout<<"Please input the main String:"<<endl;
  30.    gets(S);
  31.    //cin.get(S,MAX_STRLEN);
  32.    cout<<"Please input the position and length of SubString:"<<endl;
  33.    cout<<"position="<<endl;
  34.    cin>>pos;
  35.    cout<<"length="<<endl;
  36.    cin>>len;
  37.    if(SubString(Sub,S,pos,len))
  38.        { 
  39.           cout<<"The SubString is_="<<Sub+1<<endl;
  40.           //cout<<"SubString.length= "<<Sub[0]<<endl;
  41.           printf("SubString.length= %d/n",Sub[0]);
  42.              
  43.        }
  44.    getchar();
  45.    Sub[i]=NULL;
  46.    S[i]=NULL;
  47.    }
  48.    
  49.    return 0 ;
  50. }