【问题标题】:Why doesn't this loop want to work properly?为什么这个循环不想正常工作?
【发布时间】:2014-11-10 23:12:39
【问题描述】:

我已经在这里工作了好几个小时,但我希望能够添加另一个潜水员,我唯一需要展示的是被评判的潜水员数量和他们的平均分数,一旦这个问题我可以做是固定的。

它运行,但是当它循环时,它会跳过城市,并最终在第二到第三次崩溃。 有人可以帮忙吗?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main(){
    string name;
    string city;
    double judge[4];

    double total = 0;
    double score;
    int divers = 1;
    int x = 0;
    int y = 1;

    do{
        cout << "Please enter divers name: ";
        getline(cin, name);
        cout << "Enter the diver's city: ";
        getline(cin, city);

        do{
            cout << "Enter the score given by judge #" << y << ": " ;
            cin >> judge[x];

            total = total + judge[x];

            y++;
            x++;
        } while(y < 6);

        y = 1;

        cout << "Divers?";
        cin >> divers;

    } while(divers == 1);

    cout << city << endl;
    cout << name << endl;
    cout << total << endl;
    cout << judge[0] << endl;
    cout << judge[1] << endl;
    cout << judge[2] << endl;
    cout << judge[3] << endl;
    cout << judge[4] << endl;

    system("PAUSE");
}

【问题讨论】:

  • 您想添加潜水员,而您的代码只接受一个潜水员 (while(divers == 1))....while(condition is not true) 是 do-while 循环的工作方式。这有帮助吗?
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange (SE) 网络上发帖,您已根据 CC BY-SA license 授予 SE 分发内容的不可撤销权利(即无论您未来的选择如何)。根据 SE 政策,分发非破坏版本。因此,任何破坏行为都将被撤销。请参阅:How does deleting work? …。如果允许删除,则帖子下方左侧有一个“删除”按钮,但仅在浏览器中,而不是移动应用程序中。

标签: c++ string loops while-loop


【解决方案1】:

索引从 0 开始,声明 judge[4] 意味着您的 judge 索引为 0 1 2 3。您正在访问数组末尾之外的内容。

【讨论】:

  • 数组大小声明不是从0开始的,如果要5个判断,使用'double Judge[5]'
  • @Aarix " 我在其他任何地方都得不到这样的帮助。" 奇怪的是,你根本不应该在这里得到这样的帮助。 IE。您的问题本身对其他人没有帮助(反对票清楚地表明了这一点)。
【解决方案2】:

当您执行cin &gt;&gt; divers; 时,不会从输入中删除行尾字符,只会删除前面的数字。然后,下次您请求带有std::getline() 的行时,它只返回已经存在的行尾字符,并且不会等待您的新输入。

因此,当您进行cin &gt;&gt; drivers 样式输入在 std::getline() 样式输入之前,您需要阅读行尾字符。

一种方法是使用ignore() 函数:

do{
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    cout << "Please enter divers name: ";
    getline(cin, name);
    cout << "Enter the diver's city: ";
    getline(cin, city);

    // ...

另一种方法是在您的std::getline() 调用中使用空白食者std::ws:

do{
    cout << "Please enter divers name: ";
    getline(cin >> std::ws, name);
    cout << "Enter the diver's city: ";
    getline(cin >> std::ws, city);

    // ...

严格来说只有第一个是必要的。请记住,吃空白符会吃掉您在getline() 中键入的所有初始空格,因此如果您使用该技术,您将无法读取前导空格。

【讨论】:

  • 您只有 4 个 Judge[] 位置,并且您循环了 5 次(我认为)。请记住,数组从0 开始计数,因此您的 4 个 Judge[] 位置是:judge[0]; judge[1]; judge[2]; judge[3]。所以0-3。如果i 高于 3,那么您将访问数组的末尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
相关资源
最近更新 更多