【问题标题】:adding two single chars in c++在 C++ 中添加两个单个字符
【发布时间】:2014-10-29 16:22:02
【问题描述】:

我正在尝试用 C++ 制作自动售货机。我只是想向它添加一些验证,这样它就不会中断。我首先要求用户输入他们选择的前两个字母。我知道我不能阻止他们输入超过一个字符。我创建了一个 do while 循环以确保第一个字符和第二个字符不大于 maxChar。我没有得到任何语法错误,但我没有得到正确的答案。我知道 char 与 int 不同,但我如何将 char 转换为 int?任何帮助将不胜感激

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <set>
#include <cctype>
#include <locale>


const int maxChr = 3;
char chrOne,chrTwo; 
   do
    { 
        cin >>chrOne>>chrTwo;
        if(chrOne + chrTwo > maxChr)
        {
            cout <<"you have too many characters"
            "please try again" << endl;
        } 
        while (chrOne + chrTwo > maxChr);  

    }

【问题讨论】:

  • 所以...'A' + 'B' 肯定会大于 3。
  • 你是在总结字符的,以确定用户输入了多少???
  • 我很困惑。您的意思是验证输入了 多少 个字符或输入了 哪些 个字符?
  • 你想让用户输入2个值吗?
  • “我没有得到正确答案” - 你得到什么答案?你认为哪个答案应该是正确的?你的意见是什么?

标签: c++ char int add


【解决方案1】:

do...while 循环看起来像:

do
{

} while ();

(你的 while 在结束括号之前)

如果您只想获取两个字符(假设您只想要 0-9,因为您要求输入有问题的数字):

#include <iostream>

int main()
{

  char in1,in2;
  do {
      std::cout << "please make a selection"
      cin.get(in1); 
      cin.get(in2);
      in1 -= '0'; //converts a char to the digit that represents it - needs checking though
      in2 -= '0';
      //at this point, you have grabbed both the inputs from the cmdline.
      //you'll need to ensure that these are valid.
  } while (!(in1 >= 0 && in1 <= 9 && in2 >= 0 && in2 <= 9)); //change as needed e.g. if you have a 5*6 machine, reduce the '9's to 5 and 6

  //you now have your input.
}

【讨论】:

  • 这个问题是tagget c++。将getchar() 更改为cin
  • @Quest 完成。现在使用cin.get(char&amp;) 每次只抓取一个字符。
【解决方案2】:

好的,我明白你在做什么,但你做得不好......你总是会读前两个字符!


这条线chrOne + chrTwo 不是您所期望的。 ASCII 中的A 与 65 相同,B = 66 等等。所以实际上你是在对两个数字求和。 65+66 = 131,大于3;


我不知道 StackOverflow 上的格式是否错误,但 while(...) 应该在 } 之后。此代码不应编译。

【讨论】:

    【解决方案3】:

    if(chrOne + chrTwo &gt; maxChr) 行不检查用户是否输入了两个以上的字符,所以根据我的理解你说这是错误的。如果您只想要一个字符,您可以用户输入一个字符串并对此进行检查以查看用户输入了多少字符。

    【讨论】:

      【解决方案4】:

      你正在使用

      cin >>chrOne>>chrTwo;
      

      假设用户输入了两个以上的字符,即荒谬的问题。

      即使这样,您的变量中也只会存储前两个字符,即

      chrOne='a'
      chrTwo='b'
      

      请说明你打算做什么......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-27
        • 1970-01-01
        • 2021-05-25
        • 2011-04-22
        • 1970-01-01
        • 2015-07-14
        • 2023-04-08
        • 2013-11-11
        相关资源
        最近更新 更多