使用for循环后出现段错误
Segmentation fault after using for loop
下面是我的 code.It 如果我注释 for 循环但运行得很好,但是当我添加 for 循环时,它给出了一个分段错误,甚至 for 循环之前的代码也没有显示任何输出。
如果 for 循环中有问题,那么它至少应该在循环开始之前显示一些输出。
同样在这里我使用 getline 因为我的字符串包含空格。
P.S。我的错误是在循环中,我的 I 可能超过字符串长度,但它与循环开始前的分段错误有什么关系,它至少应该打印长度。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin.ignore();
getline(cin,s,'\n');
int len=s.length();
cout<<len;
int curr_len=0;
int prev_len=0;;
int count=1;
int max=1;
for(int i=0;i<len;i++)
{
cout<<s[i];
while(s[i]!=' ')
{
curr_len=curr_len+1;
i=i+1;
}
if(curr_len==prev_len)
{
count=count+1;
if(count>max)
max=count;
}
else
{
count=1;
}
while(s[i]==' ')
{
i=i+1;
prev_len=curr_len;
curr_len=0;
}
}
cout<<s<<endl;
}
}
while(s[i]!=' ')
{
curr_len=curr_len+1;
i=i+1;
}
我认为这是你的问题。
想想当 s[i] 是行尾时会发生什么。
问题在于您没有测试嵌套 while
循环中的 i
越界:
例如:
while (s[i] != ' ')
应该是:
while (s[i] != ' ' && i < len)
假设 i
几乎位于输入字符串的末尾,并且输入字符串中从 i
指向的位置开始不再有 space 个字符。这个 while
循环将继续下去,直到它找到一个 space 字符。这可能超出字符串的长度数百甚至数千字节。
一旦您将此更改应用于此 while 循环以及您未执行此检查的所有其他循环,程序应该 运行(结果是否正确是另一回事)。
下面是我的 code.It 如果我注释 for 循环但运行得很好,但是当我添加 for 循环时,它给出了一个分段错误,甚至 for 循环之前的代码也没有显示任何输出。 如果 for 循环中有问题,那么它至少应该在循环开始之前显示一些输出。 同样在这里我使用 getline 因为我的字符串包含空格。 P.S。我的错误是在循环中,我的 I 可能超过字符串长度,但它与循环开始前的分段错误有什么关系,它至少应该打印长度。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin.ignore();
getline(cin,s,'\n');
int len=s.length();
cout<<len;
int curr_len=0;
int prev_len=0;;
int count=1;
int max=1;
for(int i=0;i<len;i++)
{
cout<<s[i];
while(s[i]!=' ')
{
curr_len=curr_len+1;
i=i+1;
}
if(curr_len==prev_len)
{
count=count+1;
if(count>max)
max=count;
}
else
{
count=1;
}
while(s[i]==' ')
{
i=i+1;
prev_len=curr_len;
curr_len=0;
}
}
cout<<s<<endl;
}
}
while(s[i]!=' ')
{
curr_len=curr_len+1;
i=i+1;
}
我认为这是你的问题。 想想当 s[i] 是行尾时会发生什么。
问题在于您没有测试嵌套 while
循环中的 i
越界:
例如:
while (s[i] != ' ')
应该是:
while (s[i] != ' ' && i < len)
假设 i
几乎位于输入字符串的末尾,并且输入字符串中从 i
指向的位置开始不再有 space 个字符。这个 while
循环将继续下去,直到它找到一个 space 字符。这可能超出字符串的长度数百甚至数千字节。
一旦您将此更改应用于此 while 循环以及您未执行此检查的所有其他循环,程序应该 运行(结果是否正确是另一回事)。