2014-03-02 114 views
0

我正在创建一个程序来收集最多10个字符的字符数组。然后它要求用户输入一个字符。如果找到该字符,它将删除该字符数组中的所有条目,并向前移动数组中剩余的字符以消除所有间隙。从字符数组中删除条目

这是代码我目前:

for (int n = 0; n == 10; n++) 
{ 
    int index(0); 
    **while (text[index] != EOT) 
    { 
     if (text[index] == letter) 
     { 
      while (text[index] != EOT) 
      { 
       text[index] = text[index + 1]; 
       index++; 
      } 
     } 
     else 
      index++; 
    }** 
} 

粗体显示的代码(或与**这间*当前工作,并删除用户输入的字符的第一个实例所以我。因为输入限制为10个字符,它会(或应该)工作吗?

但是它什么都不做了。它甚至不会删除角色的第一个实例,它真的让我感到莫名其妙。任何人都可以看到我出错的地方吗?

这是c + +,我用的方式使用Visual Studios 2013。

谢谢!

+0

为什么不只是一个'std :: string'和'std :: remove'? – chris

+0

我从来不知道那个存在 - 我还没有被教过!我现在要研究它,谢谢! – Craig

回答

3

这个循环

for (int n = 0; n == 10; n++) 

的控制语句意味着该循环将永远不会被执行。您将零分配给n,然后说:“在n等于10时执行循环”。但是,n为回答:“我不等于10” :)

你可以执行的任务更简单的使用标准算法std::remove

例如

#include <algorithm> 
#include <cstring> 
//... 

*std::remove(text, text + std::strlen(text), letter) = '\0'; 
+0

神圣的废话谢谢你。我很少使用循环,因为你可能会告诉!我将==更改为<,现在它工作!谢谢你指出:) – Craig

+0

也谢谢你指出std :: remove,我现在应该看看和研究! – Craig

0

你应该用std: :矢量,这对你来说更容易。

for(std::vector<char>::iterator it = vect.begin() ; it != vect.end() ; it++) 
{ 
    if((*it) == letter) 
    { 
     vect.erase(it); 
    } 
} 
+0

这是重复删除删除语言的不正确尝试。 – chris

0

你的问题,因为你使用的是相同的index变量循环中两个不同的地方

for (int n = 0; n == 10; n++) 
{ 
    int index(0); 
    **while (text[index] != EOT) // loop 1 
    { 
     if (text[index] == letter) // loop 1 
     { 
      while (text[index] != EOT) // loop 2 
      { 
       text[index] = text[index + 1]; // loop 2 
       index++;    // loop2 
      } 
     } 
     else 
      index++; // loop 1 
    }** 
} 

改变你的代码

for (int n = 0; n == 10; n++) 
{ 
    int index(0); 
    while (text[index] != EOT) 
    { 
     if (text[index] == letter) 
     { 
      int index2(index); 
      while (text[index2] != EOT) 
      { 
       text[index2] = text[index2 + 1]; 
       index2++; 
      } 
     } 
     else 
      index++; 
    } 
} 
0

我建议以下解决方案:

std::string text; 
char charToBeRemoved; 

text.erase (std::remove(text.begin(), text.end(), charToBeRemoved), text.end()); 
0

当你做你的循环时,你检查你的变量n错误。

for (int n = 0; n == 10; n++) 

应该

for (int n = 0; n < 10; n++) 

这将循环十倍。