为什么这个简单的程序会出现分段错误?
我写了一个简单的C++程序。这个想法是,一旦它看到一个非字母字符,那么直到它看到一个新单词(空白)或字符串结束时,它就会继续递增迭代器。
这会产生分段错误,不知道为什么:( 请帮忙。
#include <iostream>
using namespace std;
int main()
{
string str("Hello yuio");
string::iterator it=str.begin();
while(it!=str.end())
{
cout << *it << endl;
if(isalpha(*it)==0){
cout << *it << ":Is not an alphabet\n";
while((*it!=' ')||(it!=str.end()))
{
cout << *it << endl;
it++;
}
}
if(it!=str.end()){it++;}
} // while loop ends
} // End of main
I have written a simple C++ program. The idea is, once it sees a non-alphabetic character, then till the time it see a new word (a blank) or the string ends, it keeps on incrementing the iterator.
This generates Segmentation fault, no idea why :(
Please help.
#include <iostream>
using namespace std;
int main()
{
string str("Hello yuio");
string::iterator it=str.begin();
while(it!=str.end())
{
cout << *it << endl;
if(isalpha(*it)==0){
cout << *it << ":Is not an alphabet\n";
while((*it!=' ')||(it!=str.end()))
{
cout << *it << endl;
it++;
}
}
if(it!=str.end()){it++;}
} // while loop ends
} // End of main
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
*it
在检查it
本身是否可以使用之前进行评估。更改为:*it
is evaluated before checking ifit
itself is ok to use. Change to:上面的行包含两个错误。
条件表示当前字符不是空格或尚未到达字符串末尾时循环应继续。即,即使到达末尾但当前字符不是空格,循环也会继续。
一旦修复了此错误(通过将
||
替换为&&
),您仍然会尝试取消引用结束迭代器(因为空间检查来自 <在检查字符串结尾之前),这是不允许的。您必须切换条件的顺序:while((it!=str.end()) && (*it!=' '))
The line above contains two errors.
The condition says that the loop shall go on while the current character is not a space OR end of string is not reached yet. I.e., even when the end is reached but current char is not a space, the loop will proceed.
Once you fixed this error (by replacing
||
with&&
), you still try to dereference the end iterator (because the check for space comes before the check for end of string), which is not allowed. You have to switch the order of conditions:while((it!=str.end()) && (*it!=' '))
问题就在这里:
当到达字符串末尾时,条件的第一部分为 true,因此您继续循环并递增迭代器。
您需要替换为
&&
:The problem is here:
When you reach the end of the string, the first part of the condition is true and so you continue looping and incrementing the iterator.
You need to replace with
&&
: