在c++中的字符串类数组中不打印任何内容,即使我可以访问单个元素

printing nothing in string class array in c++ even though I can access individual elements

本文关键字:我可以 访问 元素 单个 打印 字符串 c++ 数组 任何内      更新时间:2023-10-16

即使我可以在str1[I].a中打印字符串str2[I].a在按索引值打印字符串时,我正在获取字符串中的各个字符我还可以打印str1[I].一个我以前输入的字符串谢谢

     #include <iostream>
     #include <vector>
     #include <string>
     using namespace std;
        class st
     {
        public:
           string a;
           int col;
     }str1[200],str2[200];

     int main()
    {
        int i=0,j=0,num,l=0,len=0;
        string str;
        for(i=0;;i++)
       {
           cin>>num;
           str1[i].col=num;
           if(str1[i].col==0)
                break;
           cin>>str1[i].a;
           cout<<str1[i].a; // I get string entered before                    
      }

      for(i=0;;i++)
      {   
             if(str1[i].col==0)
                  break;
             len = str1[i].a.size()-1;
             //cout << len << endl;
             l=0,j=0;
             for(;;)
            {
                 str2[i].a[l]=str1[i].a[j];
                 l++;
                 j=((j+str1[i].col)%len);
                 if(j==0)
                   {
                      str2[i].a[l]=str1[i].a[len];
                      cout << str2[i].a[l];//I get the char assigned above
                      l++;
                      str2[i].a[l]='n';
                      break;
                   }
             }

          cout << str2[i].a; // I get nothing after I print
          cout << str2[i].a[0];// I get the required character of string
          cout << str2[i].a[5];//I get the required character of string
          cout << str2[i].a[8];//I get the required character of string
         }

       return 0;
    }

您忘记了为第二个字符串预先分配缓冲区。只有当std::string中的一个字符串至少有那么多字符时,才可以安全地将值分配给该字符串(换句话说,str2.a[2] = 'a'是安全的,因为std2.a的长度至少为三个,但如果长度较小,则不安全)。在您的情况下,没有一个str2被分配任何东西,所以它们都是空的,长度为0

一种解决方案是提前预分配字符串,但更好的是,由于只将字符写到末尾,因此使用push_back而不是中的方括号

str2[i].push_back(str1[i].a[j]);

而不是

str2[i].a[l]=str1[i].a[j];

为了解释为什么你可以打印单个字符,但不能打印整个字符串,请注意,从技术上讲,你所做的是一种未定义的行为[1],我假设当你打印整个字符串时,它会查看其长度,发现它为零,并跳过打印任何内容,但当你打印单个字符时,它查看为字符串分配的缓冲区(可能大小为非零,以使早期的push_back有效),并查看您对它们所做的更改。

[1]http://www.cplusplus.com/reference/string/string/operator%5B%5D/,特别参见:

如果pos小于字符串长度,则函数从不抛出异常(无抛出保证)。如果pos等于字符串长度,const版本从不抛出异常(没有抛出保证)。否则,会导致未定义的行为