【问题标题】:Input strings and display reversely using for loops with arrays使用带有数组的 for 循环输入字符串并反向显示
【发布时间】:2014-10-12 09:02:15
【问题描述】:

我要做的是输入一些循环,然后所有输入的单词都会反向显示。我尝试将数字显示在相反的位置,它可以正常工作。但是,我不知道要在代码中更改什么。我c++不好,所以在练习。谢谢你帮助我=)

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int x, y;
    string a[y];
    cout << "Enter number: ";
    cin >> x;
    x=x-1;
    for (y=0; y<=x; y++)
    {
        cout << y+1 << ". ";
        cin >> a[y];
    }
    for (y=x; y>=0; y--)
    {
        cout << a[y] << endl;
    }
    return 0;
}

【问题讨论】:

  • 你想输入一个字符串然后以相反的顺序打印那个字符串吗??
  • 这是未定义的:string a[y]; 你需要至少在cin &gt;&gt; x; x=x-1; 之后放置这一行
  • @kempoy211 正如我在帖子中指出的那样,C++ 没有可变长度数组。因此,您将答案标记为使用 VLA 的最佳答案。也就是答案中给出的代码不满足C++标准,不能被其他编译器编译。
  • @VladfromMoscow 对不起,我想我可以标记两个答案。对不起

标签: c++ arrays string for-loop


【解决方案1】:

您的 ptogram 无效。例如,您要声明数组 a

string a[y];

虽然变量 y 未初始化

int x, y;

C++ 不允许定义可变长度数组。

所以使用标准容器std::vector而不是数组会更好

程序可能如下所示

#include <iostream>
#include <vector>
#include <string>

int main() 
{
    std::cout << "Enter number: ";

    size_t n = 0;
    std::cin >> n;

    std::vector<std::string> v;
    v.reserve( n );

    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << i + 1 << ". ";

        std::string s;
        std::cin >> s;
        v.push_back( s );
    }

    for ( size_t i = n; i != 0; i-- )
    {
        std::cout << v[i-1] << std::endl;
    }

    return 0;
}

例如,如果输入看起来像

4
Welcome
to
Stackoverflow
kempoy211

那么输出将是

kempoy211
Stackoverflow
to
Welcome

【讨论】:

  • 非常感谢!你知道什么是了解 C++ 更多信息的最佳网站吗?抱歉后续问题。谢谢 ! =)
  • @kempoy211 我不使用网站来学习 C++。我只有在有问题时才会浏览网站。所以我不能建议一个学习 C++ 的网站。
  • 我可以使用预处理器 fstream 将所有输入的字符串发送到数据库吗?然后,当我想查看我的数据库时,我可以将它们发送回程序吗?我的意思是,显示或查看它。
  • @kempoy211 什么是“预处理器 fstream”?当然你可以写和读文件。
【解决方案2】:

您可以在 C++ 中使用算法库中的 std::reverse。这样你就不需要编写这些庞大的循环了

已编辑:-

如果你只是想要一个反向遍历并在下面打印你的字符串是伪代码:-

for ( each string str in array )
{
for ( int index = str.length()-1; index >= 0; index -- )
cout << str[index];
}
cout <<endl;
}

【讨论】:

  • 不是真的,std::reverse 会改变容器,OP 要求反向遍历
【解决方案3】:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int x, y;
    cout << "Enter number: ";
    cin >> x;
    string a[x];  //this should be placed after cin as x will then be initialized
for (y=0; y<x; y++)
    {
        cout << y+1 << ". ";
        cin >> a[y];
    }
for (y=x-1; y>=0; y--)  // x-1 because array index starts from 0 to x-1 and not 0 to x
    {
        cout << a[y] << endl;
    }
return 0;
}

输出:

Enter Number: 5
1. one
2. two
3. three
4. four
5. five
five
four
three
two
one

【讨论】:

  • 我可以使用预处理器 fstream 将输入和扫描的字符串发送到数据库吗? TIA。
猜你喜欢
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 2020-05-22
  • 2021-07-21
  • 1970-01-01
  • 2013-11-02
  • 2022-06-27
相关资源
最近更新 更多