这是来自Stroustrups"编程:原理和实践使用C ++"的自学问题。我有第二版。如果已经回答,请随时提供链接,因为我发现没有任何链接直接与此问题的要求相关联。
构建一个输入"零" - "九"或0-9并将其转换为字符串或数字形式。
我已经成功地将数字转换为单词形式,但是对于明智的人来说,没有正确的结构。这是本书的一个阶段,其中只引入了if / for / while语句,运算符和向量等基础知识。如果这个问题不符合本论坛的期望,请告诉我,因为我正在认真学习这门语言。
(我已禁用此时未计算的代码部分)
#include "C:\Users\***********\Documents\Visual Studio 2017\Projects/std_lib_facilities.h"
int main() {
/**int zero;
string one;
string two;
string three;
string four;
string five;
string six;
string seven;
string eight;
string nine;
**/
int input;
vector<string>words =
{"zero","one","two","three","four","five","six","seven","eight","nine"};
cout << "Please enter a number between 0 and 9" << '\n';
cin >> input;
if ((input == 0) || (input == 1) || (input == 2) || (input == 3) || (input == 4) || (input == 5) || (input == 6) || (input == 7) || (input == 8) || (input == 9)) {
cout << words[input] << '\n';
}
}
/**if ((input == zero) || (input == one) || (input == two) || (input == three) || (input == four) || (input == five) || (input == six) || (input == seven) || (input == eight) || (input == nine)) {}
**/
答案 0 :(得分:0)
我不是完全确定这对C ++来说是一个很好的问题,因为只使用该语言的遗留C部分相对容易。
但是,我会做几个笔记:
std::array
,因为它带有大小信息。main
中创建所有内容。我建议使用两个单独的函数,一个用于字符串到int,另一个用于另一种方式。if
构造,而应该使用库设施来简化生活(是的,即使是传统的C语言,如果它们可以达到目的)。为此,您可能需要检查以下示例程序,该程序将为您提供所需的功能:
#include <iostream>
#include <array>
#include <cstring>
namespace {
// Only visible to this unit, make const to return as ref.
const std::array<const std::string, 10> words = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
const std::string empty;
}
// Convert a word to numeric value, -1 if no good.
int toInt(const std::string &num) {
// Just check all possible words.
for (int i = 0; i < words.size(); ++i)
if (num == words[i])
return i;
return -1;
}
// Convert a single-digit numeric string to word string, empty if invalid.
const std::string &toStr(const std::string &num) {
// Must be single numeric character.
if ((num.size() != 1) || (strchr("0123456789", num[0]) == nullptr))
return empty;
return words[num[0] - '0'];
}
// Simple test harness, just check all arguments passed.
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) {
int asInt = toInt(argv[i]);
if (asInt >= 0) {
std::cout << "'" << argv[i] << "' as numeric = " << asInt << std::endl;
} else {
std::string asStr = toStr(argv[i]);
if (! asStr.empty()) {
std::cout << "'" << argv[i] << "' as alpha = " << asStr << std::endl;
} else {
std::cout << "*** '" << argv[i] << "' is not valid input" << std::endl;
}
}
}
return 0;
}