输入1到7的数值,输出相应的英文单词。分别使用指针数组和string实现
时间: 2024-05-09 09:17:31 浏览: 4
使用指针数组实现:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string words[] = {"one", "two", "three", "four", "five", "six", "seven"};
int n;
cin >> n;
if (n >= 1 && n <= 7) {
cout << words[n-1] << endl;
}
return 0;
}
```
使用 string 实现:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string words[] = {"", "one", "two", "three", "four", "five", "six", "seven"};
int n;
cin >> n;
if (n >= 1 && n <= 7) {
cout << words[n] << endl;
}
return 0;
}
```
相关问题
输入一个1~7的数值,然后输出相应的英文单词;要求分别使用指针数组和string类实现
好的,我能够帮您回答这个问题。
指针数组实现:
```
#include <iostream>
using namespace std;
int main()
{
const char *nums[] = {"one", "two", "three", "four", "five", "six", "seven"};
int num;
cout << "请输入一个1~7的数值:" << endl;
cin >> num;
if (num >= 1 && num <= 7)
{
cout << nums[num-1] << endl;
}
else
{
cout << "输入的数值不正确!" << endl;
}
return 0;
}
```
string类实现:
```
#include <iostream>
#include <string>
using namespace std;
int main()
{
string nums[] = {"one", "two", "three", "four", "five", "six", "seven"};
int num;
cout << "请输入一个1~7的数值:" << endl;
cin >> num;
if (num >= 1 && num <= 7)
{
cout << nums[num-1] << endl;
}
else
{
cout << "输入的数值不正确!" << endl;
}
return 0;
}
```
以上代码中,我使用了指针数组和string类分别实现了根据数字输出相应的英文单词。在指针数组中,我定义了一个常量字符指针数组,然后根据输入的数字输出相应的字符串;在string类中,我定义了一个字符串数组,同理根据输入的数字输出相应的字符串。
输入一个1~7的数值,然后输出相应的英文单词;要求分别使用指针数组和string类实现。
好的,这个问题是技术问题,我可以回答。以下是使用指针数组和string类实现的代码示例:
使用指针数组实现:
```c++
#include <iostream>
using namespace std;
int main() {
const char* numWords[] = {"", "one", "two", "three", "four", "five", "six", "seven"};
int num;
cout << "Enter a number between 1 and 7: ";
cin >> num;
if (num >= 1 && num <= 7) {
cout << numWords[num] << endl;
} else {
cout << "Invalid input" << endl;
}
return 0;
}
```
使用string类实现:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string numWords[] = {"", "one", "two", "three", "four", "five", "six", "seven"};
int num;
cout << "Enter a number between 1 and 7: ";
cin >> num;
if (num >= 1 && num <= 7) {
cout << numWords[num] << endl;
} else {
cout << "Invalid input" << endl;
}
return 0;
}
```