简体   繁体   English

需要一些帮助在我的while循环中发现逻辑错误

[英]Need some help finding a logical error in my while loop

I am learning C++, and I am doing some exercises in the book I am using. 我正在学习C ++,并且正在使用的书中做一些练习。 One of them asks to write a program that asks a user how many numbers they want to add up. 其中一个要求编写一个程序,询问用户要累加多少个数字。 Then prompt for the numbers the user wants to add or to enter '|' 然后提示用户要添加的数字或输入“ |” once finished. 一旦完成。 The numbers are then pushed into a vector. 然后将数字压入向量。 Part of the program asks to check if the size of the vector is equal to the original number of input items and that is where I keep getting an error. 该程序的一部分要求检查向量的大小是否等于输入项的原始数量,而这就是我不断收到错误的地方。

cout << "Please enter the numbers and | once you are done: ";

while(true)
{

    for(int num; cin >> num; )
    {
        if(num == '|')
        {
            break;
        }

        ints.push_back(num);
    }

    if(ints.size() != n)
    {
        cout << "There are more or less numbers in the vector than originally specified\n"
            << "Vector will be cleared; please re-enter the values: ";
        ints.clear();
        continue;
    }
    else
    {
        break;
    }
}

The problem is that if the number of input is off, the message goes into an infinite loop and I am not sure how to fix it. 问题是,如果输入数量关闭,则消息将陷入无限循环,并且我不确定如何解决。

EDIT: n is the variable that holds in the number of values user wanted to enter. 编辑:n是保存在用户想要输入的值数中的变量。

Thanks! 谢谢!

num is an integer and cin >> num won't extract | num是一个整数,并且cin >> num不会提取| symbol. 符号。 Comparison num == '|' 比较编号num == '|' may not work as expected because num could have the numeric value of | 可能无法正常工作,因为num的数值可能是| ascii symbol even when user did not input any | ASCII符号,即使用户未输入任何符号| symbol. 符号。 You should properly handle end marker reading: 您应该正确处理结束标记读取:

// loop will break when user enters `|` because it is not an integer
// setting failbit of cin
for(int num; cin >> num;)
{
    ints.push_back(num);
}
cin.clear(); // reset failbit making cin able to read again
// check the end marker entered by user
{
    string end_marker;
    cin >> end_marker;
    if("|" != end_marker)
    {
        // use of endl will flush the stream ensuring that
        // printed text won't stuck in the buffer
        cout << "Please use | as end marker" << endl;
        continue;
    }
}

Here is how I implemented it. 这是我的实现方法。 I am worried about the logic in your while loop. 我担心您的while循环中的逻辑。 I had been taught to avoid while(true) whenever possible. 我被教导要尽可能地避免while(true) You know the logic behind how your code should work. 您知道代码应该如何工作的逻辑。 With more practice you'll start to recognize the conditions you need to use. 通过更多的练习,您将开始认识到需要使用的条件。 I am sure there are better ways to do it. 我相信有更好的方法可以做到这一点。 But this is the way I tried it. 但这是我尝试的方式。

But to answer your question, the main reason it is failing is because integers cannot compare themselves with characters. 但是要回答您的问题,它失败的主要原因是因为整数无法将自己与字符进行比较。

if(num == '|') 

That does not work since num is an integer and not a character. 这是行不通的,因为num是整数而不是字符。

Normally I would implement this in a class and since global variables are not highly looked upon I created my own namespace. 通常,我会在一个类中实现它,并且由于对全局变量的关注度不高,所以我创建了自己的命名空间。 You'll have to finish the rest of the logic yourself however: 但是,您必须自己完成其余的逻辑:

#include <iostream>
#include <vector>
#include <string>

namespace global
{
    std::vector<std::string> strings;
    std::vector<int> ints;
    std::string a = " ";
    int num = 0;
}   

void doWork()
{   

    std::cout << "Please enter the number of integers you would like to add up: ";
    std::cin >> global::num;

    std::cout << "Please enter the numbers and | once you are done: ";
    while (global::a != "|")
    {
        std::cin >> global::a;
        global::strings.push_back(global::a);
    }

    global::strings.pop_back();

    for(auto &e : global::strings)
    {
         global::ints.push_back(std::stoi(e));
    }
}   


int main()
{

    doWork();

    if(global::ints.size() != global::num)
    {
        std::cout << "Size of vector does not match the size specified. Clearing vector" << std::endl;
        global::ints.clear(); 
        global::strings.clear();
        global::num = 0;
        global::a = " ";
        doWork();
    }   

}

I made a vector of char's and converted those into integers so that way you could add them up. 我制作了一个char的向量并将其转换为整数,以便可以将它们相加。 The while loop should be checking for | while循环应检查| rather than always running true. 而不是始终如一。 It then will check the size of the vector in the end, clear it if it does not match, and ask you to do it again. 然后它将最后检查向量的大小,如果不匹配则将其清除,然后要求您再次进行。 This is the best way that I could think of doing it. 这是我想到的最好方法。

EDIT: as VTT pointed out, char can only do one character at a time. 编辑:正如VTT所指出的, char一次只能做一个字符。 I have converted it into a string in order to handle the conversion. 我已将其转换为字符串以处理转换。

EDIT 2: reset the values of global::num and global::a to their default at the end of the failure in order to prevent crashing. 编辑2:在故障结束时将global::numglobal::a的值重置为其默认值,以防止崩溃。

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

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