我的代碼如下。我希望用戶能夠輸入任意數量的運算元,然后代碼要求他們輸入該次數的運算元。我已經弄清楚了那部分。我如何在不知道他們想要多少的情況下存盤他們的每個運算元?
for (int i = 0; i < numoperands; i ){
cout << "Input Operand: ";
cin >> ;
uj5u.com熱心網友回復:
您是否需要為每個不同的輸入設定一個單獨的變數?
如果不是,您可以嘗試在 for 回圈外定義一個陣列,然后在 for 回圈內為用戶的每個輸入附加到陣列。
當您想訪問運算元時,只需為陣列的長度運行另一個 for 回圈并對其進行索引。
uj5u.com熱心網友回復:
您需要更多的“構建”塊才能讓您的程式正常作業:
- 回圈,允許您的代碼多次運行相同的代碼(while 和 for 回圈)
- 停止條件,你什么時候停止接受輸入
- 轉換,從字串到整數
- 字串,保存輸入
在繼續之前,我建議您先學習更多 C 。如果您沒有任何書籍,這可能是一個不錯的起點:https : //www.learncpp.com/
示例說明:
#include <iostream>
#include <string> // include standard library type for a string.
#include <vector> // a vector can hold values (or objects) and can grow at runtime
// DO NOT use : using namespace std;
// It is good to unlearn that right away https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
int main()
{
std::string input; // a string to receive input in.
std::vector<int> values; // C does know about arrays, but they are fixed length,
// vector vector is allowed to grow
const std::string end_input{ "x" }; // const means you will only read from this variable
// the "x" is used to end the input
// start a do/while loop. Allows you to run the same code multiple times
do
{
// prompt the user what to do :
std::cout << "Enter a number ('"<< end_input << "' to end input) and press return : ";
// read input to the string so we can check its content
std::cin >> input;
// check input end condition
if (input != end_input)
{
int value = std::stoi(input); // stoi is a function that converts a string to an integer
values.push_back(value); // push back adds value at the end of the vector
}
} while (input != end_input); // if condition is not met, then program continues at do (and thus loops)
// the next lines output the content of the vector to show the input
std::cout << "\n"; // output a new line (avoid std::endl)
std::cout << "Your input was : \n";
bool print_comma = false;
for (int value : values) // loops over all values in the vector
{
if (print_comma) std::cout << ", ";
std::cout << value;
print_comma = true;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388296.html
