C++ 为什么字符串的行为在这里不同?为什么第一个for循环不打印任何内容,第二个for循环正确打印输出
在这个C++ 为什么字符串的行为在这里不同?为什么第一个for循环不打印任何内容,第二个for循环正确打印输出,c++,c++11,C++,C++11,在这个字符串长度编码算法中,我无法理解字符串的奇怪行为。有人能解释一下字符串的用法吗?下面的第一个for loop不打印任何内容,而第二个打印正确。我尝试使用大小、长度和大小,但循环的第一个仍然不打印任何内容 #include <iostream> using namespace std; int main() { // your code goes here string str, newstr; str="aabcccccaaa"; newstr
字符串长度编码算法中,我无法理解字符串的奇怪行为。有人能解释一下字符串的用法吗?下面的第一个for loop
不打印任何内容,而第二个打印正确。我尝试使用大小、长度和大小,但循环的第一个仍然不打印任何内容
#include <iostream>
using namespace std;
int main() {
// your code goes here
string str, newstr;
str="aabcccccaaa";
newstr[0]=str[0];
cout<<str;
int j = 1;
for (int i =0; i<str.length(); i++)
{
int count =1;
while(i+1 != str.length() && str[i] == str[i+1])
{
count++; i++;
}
newstr[j] = '0'+count;
if(i+1 != str.length())
{ newstr[j+1] = str[i+1];
j=j+1;
}
j=j+1;
}
cout<<"\nRun String:";
for(int i =0; i<newstr.size(); i++) // First For loop.
cout<<newstr[i];
for(int i=0; i<j; i++) // Second For loop.
cout<<newstr[i];
return 0;
}
#包括
使用名称空间std;
int main(){
//你的密码在这里
字符串str,newstr;
str=“aabcccaaa”;
newstr[0]=str[0];
coutnewstr
是一个空字符串。执行此操作时
newstr[0]=str[0];
还是这个
newstr[j] = '0'+count;
newstr[j+1] = str[i+1];
还是这个
newstr[j] = '0'+count;
newstr[j+1] = str[i+1];
通过越界访问其存储来调用未定义的行为。在此之后,所有赌注都将取消。首先,修复这些错误。newstr
是一个空字符串。执行此操作时
newstr[0]=str[0];
还是这个
newstr[j] = '0'+count;
newstr[j+1] = str[i+1];
还是这个
newstr[j] = '0'+count;
newstr[j+1] = str[i+1];
您通过访问未定义的行为的存储区来调用该行为。在此之后,所有赌注都将被取消。首先,修复这些错误。理想情况下,他将使用push_back
或其他方法,而不是使用[]
,而是添加newstr.resize(str.size())
使他的程序成功运行。理想情况下,他将使用推回
或其他方法,而不是使用[]
,但添加newstr.resize(str.size());
使他的程序成功运行。