【问题标题】:Why isn't string resetting inside the loop?为什么不在循环内重置字符串?
【发布时间】:2017-07-14 04:47:22
【问题描述】:

我正在为一个班级制作一个小型桌面成本计划。我想在其中包含一个循环。但是每次我到程序结束并循环回到开头时,它都会跳过我询问客户姓名的部分并将其留空。知道如何解决吗?

这是我的代码:

#include <iostream>            // needed for Cin and Cout
#include <string>              // needed for the String class
#include <math.h>              // math functions
#include <stdlib.h>             
using namespace std;

#define  baseCost  200.00
#define  drawerPrice 30.00

int main(void)
{
    while(true)
    {
        string cname;
        char ch;

        cout << "What is your name?\n";
        getline(cin, cname);

        cout << cname;

        cout << "\nWould you like to do another? (y/n)\n";
        cin >> ch;

        if (ch == 'y' || ch == 'Y')
            continue;
        else
            exit(1);
    }

    return 0;
}

【问题讨论】:

  • 你有一个围绕 main 的 while 循环?这甚至可以编译吗? >.
  • 既然您已经确定问题出在循环和字符串上,您可以将代码简化为这样吗?这让每个人都轻松多了。 (PS:while (true) int main() { ... 什么?)
  • edit您的问题提供minimal reproducible example
  • 你的复制粘贴好像坏了。
  • 它有一个简化版本。 (抱歉,'while' 放置错误)

标签: c++ string loops while-loop


【解决方案1】:

问题是您需要在提示退出后调用 cin.ignore()。当您使用 cin 获取 'ch' 变量时,换行符仍存储在输入缓冲区中。调用 cin.ignore(),忽略该字符。

如果不这样做,您会注意到程序会在第二个循环中打印一个换行符作为名称。

您还可以将“ch”变量设为“cname”之类的字符串,并使用 getline 而不是 cin。这样您就不必发出 cin.ignore() 调用。

#include <iostream>            // needed for Cin and Cout
#include <string>              // needed for the String class
#include <math.h>              // math functions
#include <stdlib.h>
using namespace std;

#define  baseCost  200.00
#define  drawerPrice 30.00

int main()
{
    while(true)
    {
        string cname;
        char ch;

        cout << "What is your name?\n";
        getline(cin, cname);

        cout << cname;

        cout << "\nWould you like to do another? (y/n)\n";
        cin >> ch;

        // Slightly cleaner
        if (ch != 'y' && ch != 'Y')
            exit(1);

        cin.ignore();

        /*
        if (ch == 'y' || ch == 'Y')
            continue;
        else
            exit(1);
        */
    }

    return 0;
}

【讨论】:

  • 是的!谢谢。
  • 如果有机会,请点击答案旁边的复选标记。祝你学习顺利!
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多