在c++中的字符串类数组中不打印任何内容,即使我可以访问单个元素
printing nothing in string class array in c++ even though I can access individual elements
即使我可以在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版本从不抛出异常(没有抛出保证)。否则,会导致未定义的行为。
相关文章:
- 访问我以前可以访问的功能时出现分段错误
- 为什么我可以访问其他班级的私人成员?
- 我可以从标准::访问返回汽车吗?
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 我可以保证以负偏移访问指针吗?
- 我可以从C++访问包含QtObject的QQmlContext吗?
- 我可以按类类型访问哪些类型的集合,并在必要时返回未找到
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- 我可以访问唯一指针作为常量引用吗?
- 为什么我可以访问已删除但在C++中具有虚拟析构函数的对象?
- 在 OpenGL 中,我可以访问我在顶点着色器中绘制的缓冲区吗?
- 我可以访问临时对象的成员吗?
- 我可以访问Unity背景元素吗
- 当捕获boost::bad_exical_cast时,我可以访问要强制转换的字符串/令牌吗
- 在c++中的字符串类数组中不打印任何内容,即使我可以访问单个元素
- 我可以访问BOOST_LOG_TRIVIAL使用的流实例吗?
- 如果我知道一个值的地址,我可以访问它吗?
- 在g++中我可以访问哪些其他隐藏变量(使用宏预先定义的)?
- 我可以访问 std::[io]fstream 下面的文件描述符吗?
- 实现一个 dinamic 数组(我可以访问不存在的位置)