用户输入的简单c++计数器程序

User input in simple C++ counter program

本文关键字:计数器 程序 c++ 简单 输入 用户      更新时间:2023-10-16

我试图在c++中制作一个简单的计数器程序,该程序将增加用户输入的变量(通过按某个键指定)。下面是我想到的:

#include <iostream>
#include <vector> 
#include <string>
using namespace std;
int main()
{
    int variable;
    char userInput;
    variable = 0;
    cout << "To increment variable one, press a n";
    do
    {
        variable = variable++;
        cout << "variable++ n" ;
    } while (userInput = "a");
}

我在这个网站上仔细阅读了几个相关的线程,相信这应该是可行的。然而,我得到了几个错误,包括对变量的操作没有定义,以及从"const char"到"char"的"无效转换"。"

在循环中添加cin:

    cin>>userInput;

和更改

variable = variable++;

variable++; // or variable = variable + 1;

next you while条件应该像这样:

 while (userInput=='a');

所以你的整个程序看起来像这样:

#include <iostream>
using namespace std;
int main()
{
int variable;
char userInput;
variable = 0;
cout << "To increment variable one, press a n";
do
{
    cin>>userInput;
    variable++;
    cout << "variable++ n" ;
} while (userInput=='a');
return 0;
}

在while循环中需要一个std::cin,如

cin >> userInput;

此外,下面的行

variable = variable++;

将产生未定义行为。阅读更多关于序列点的信息以更好地理解。

试题:

variable = variable + 1;

最后在while循环中断条件下,代替赋值操作

while (userInput = "a");

使用比较:

while (userInput == "a");

你需要使用

std::cin >> userInput; // each time you go through the `do` loop.

同样,你只需要使用

variable++; // on the line.

也!使用cout << variable << "n";

最后,使用

} while(strncmp((const char*)userInput,(const char*)"a",1));