连续输入字符,如使用循环多次的字符串

时间:2013-03-19 16:44:50

标签: c++

在下面的代码中,我是否可能采取多个输入,进行一些计算(如最后一个字符)并在结尾打印..然后再次输入直到5次?

#include <iostream>
using namespace std;
int main ()
{
    char name;
    int i=0;
    while(i != 5){

        while(!(name != '<' || name != '>')){
            cin>>name;
            //do some calculation with the inputs
            //cout<<name;
        }
        i++;
        cout<<name;
        //print the result of calculation this loop
    }
}

由于某些原因,我不允许使用stringarraybreak,也不允许使用iostream以外的其他库。是否可以使用循环?有什么替代方案?

编辑:: 在上面的代码中,我想确定上次输入的内容。如果我输入asdf>,那么我会获得>>>>>。我希望它打印>然后回到循环中再问我一次。

3 个答案:

答案 0 :(得分:2)

解决方案是在此行之前重置名称变量:

while (!(name != '<' || name != '>')) {

你需要做的是:

name = 0;

另外,我建议在进入第一个while循环之前初始化变量。

编辑: 或者,您可以使用'\0'代替0。但内部没有任何区别。代码只会对大多数没有经验的用户更有意义。

答案 1 :(得分:2)

内部while终止后name保留<>并且在下一次遇到内部while之前未重置,这会终止name仍然是<>。只需在内部name或轻微重组之前重置while

while (cin >> name && !(name != '<' || name != '>'))
{
}

答案 2 :(得分:1)

看起来你想制作一个指向角色的指针。这样的行为就像一个数组而不是实际上是一个数组,除输入和输出#include <iostream>外只需要它。

char* name;

你也可以尝试使用一个字符向量,但这是一个很长的路要走,并打破“只有<iostream>规则:

#include <vector>
#include <iostream>

using namespace std;

vector<char> CharVec;
vector<char>::iterator it;

int main ()
{
    char input;
    int i=0;
    while(i != 5){
        if(input != '<'){ //this should be if, not while
            CharVec.push_back(input);
        }
        i++;
    }
    //move print to outside the character entering loop
    it = CharVec.begin();
    while(it != CharVec.end())
    {
        cout << *it;
        it++;
    }

}