简体   繁体   English

为什么这个简单的程序会产生分段错误?

[英]Why is this simple program giving a segmentation fault?

I have written a simple C++ program. 我写了一个简单的C ++程序。 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
while((*it!=' ')||(it!=str.end()))

*it is evaluated before checking if it itself is ok to use. *it在检查it本身是否可以使用之前进行评估。 Change to: 改成:

while((it!=str.end())&&(*it!=' '))
while((*it!=' ')||(it!=str.end()))

The line above contains two errors. 上面的行包含两个错误。

  1. 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. 该条件表明,当当前字符不是空格尚未到达字符串结尾时,循环应继续进行。 Ie, even when the end is reached but current char is not a space, the loop will proceed. 即,即使到达末尾但当前char不是空格,循环仍将继续。

  2. 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!=' '))

The problem is here: 问题在这里:

while((*it!=' ')||(it!=str.end()))

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. 当您到达字符串的末尾时,条件的第一部分为true,因此您将继续循环并递增迭代器。 You need to replace with && : 您需要替换为&&

while((*it!=' ')&&(it!=str.end()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM