从我从书中读到的内容以及我从书中所做的先前例子来看,这就是我所提出的。我很欣赏额外的建议,但我正在努力学习本章试图向我展示的内容,以便在我尝试以前从未见过的代码之前,我可以继续学习基础知识。我希望用户输入0来结束循环但由于某种原因循环继续?我想我可能会遗漏一些阻止它停止的东西。
// Ex4_08.cpp
// Initializing pointers with strings
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
bool keepgoing = true;
int answer;
while (keepgoing = true)
{
const char* pstr[]{ "Aa", // Initializing a pointer array
"Bb",
"Cc",
"Dd",
"Ee",
"Ff",
"Gg",
"Hh",
"Ii",
"Jj",
"Kk",
"Ll",
"Mm",
"Oo",
"Pp",
"Qq",
"Rr",
"Ss",
"Tt",
"Uu",
"Vv",
"Ww",
"Ss",
"Yy",
"Zz",
};
const char* pstart{ "Your letter is " };
int dice{};
cout << endl
<< "Enter a number between 1 and 26 " << _countof(pstr) << ": ";
cin >> dice;
cout << endl;
if (dice >= 1 && dice <= _countof(pstr)) // Check input validity
cout << pstart << pstr[dice - 1]; // Output star name
else
cout << "Sorry, you haven't selected a correct number."; // Invalid input
cout << "Do you want to do this again? Type 0 for no: " << endl;
cin >> answer;
if (answer == 0)
{
keepgoing = false;
}
}
cout << endl;
return 0;
}
答案 0 :(得分:0)
我使用了更多C ++且更易于使用的vector和string修改了初始代码示例:
#include <iostream>
#include <string> // for string
#include <vector> // for vector
using std::cin;
using std::cout;
using std::endl;
int main()
{
std::vector<std::string> pstr;
for (char c = 'a'; c <= 'z'; c++) // cycle over the 26 ASCII letters
{
std::string temp; //
temp += c - 32; // add capital character (e.g A)
temp += c; // add character (e.g. a)
pstr.push_back(temp); // push the new string (e.g. Aa) to the vector
}
const char* pstart{ "Your letter is " };
int dice{};
while (true)
{
cout << endl
<< "Enter a number between 1 and 26 " << pstr.size() << ": ";
cin >> dice;
if (dice == 0)
{
break; //break if the user enters 0
}
cout << endl;
if (dice >= 1 && dice <= pstr.size()) // Check input validity
cout << pstart << pstr[dice - 1]; // Output star name
else
cout << "Sorry, you haven't selected a correct number."; // Invalid input
}
cout << endl;
return 0;
}
答案 1 :(得分:0)
你的代码错了:
while (keepgoing = true) {
...
if (answer == 0) {
keepgoing = false;
}
}
您将keepgoing
设置为false,但在while
条件下,您将其置于true
。您必须使用==
运算符(如while(keepgoing == true)
中所述)或将其删除(while(keepgoing)
)。
否则,您可以使用while(true)
或for (;;)
而不是keepgoing = false
:
for (;;) { // or while (true); to me, that's only a matter of preference.
...
if (answer == 0) {
break; // exit the loop
}
}
在您输入break
条件之前,它们会产生无限循环。
答案 2 :(得分:0)
更改此行:
while (keepgoing = true)
对此:
while (keepgoing == true)
第一个将值true
指定给变量keepgoing
。对keepgoing
的值的第二次检查是true
。这是一个非常普遍的问题,许多新程序员(有时是旧程序员)的绊倒。 : - )