C++循环 - 输入整数,直到用户退出

C++ Loops - inputting integers until user quits

本文关键字:用户 退出 整数 循环 输入 C++      更新时间:2023-10-16

好吧,我试图让用户尽可能多地输入整数,直到他们输入负数。 第一步是使用 ATOF 函数将字符串转换为数字(我做到了(,然后允许用户输入整数(我只设法做一次只是为了看看我是否可以正确使用 atof 函数。

任何帮助/提示都非常感谢给我正确的方向。
这是我到目前为止的代码:

#include <iostream>
#include <string>
int main() { 
using namespace std;
char buffer[256];
char tempBuff[256] = {'n'};
double result; 
int count = 0;
cout << "Testing " << endl;
cout << "Enter Any integers: ";
cin.getline(buffer,256);
for(int i = 0; i < strlen(buffer); i++)
{
    if(isdigit(buffer[i]))
{
    tempBuff[count] = buffer[i];
    count++;
}
}
if (atof(tempBuff) > 0) { 
result = atof(tempBuff) / 2;
}
cout << endl <<  "The integer you put was: " << tempBuff 
<< " And dividing the integers  "<< result << endl;
cin.ignore();
return 0;
}

atof如何知道tempBuff包含多少个有效数字?atof函数仅接受 C 样式字符串作为其输入。否则,它无法知道有多少个字符是有效的。

您可以在调用atof之前使用tempBuff[count] = 0;。C 样式字符串以零字节结尾。