2014-10-12 44 views
1

我想要做的是输入一些循环,然后所有输入的单词将显示在相反。我试着用数字来反向显示,并且它工作正常。但是,我不知道要在代码中改变什么。我不擅长C++,所以我在练习。感谢您帮助我=)输入字符串和显示反向使用for循环与数组

#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; 
} 
+0

做哟想输入一个字符串,然后以倒序打印该字符串? – Asis 2014-10-12 09:14:15

+0

这是未定义的:'string a [y];'你需要把这行至少放在'cin >> x之后; x = x-1;' – 2014-10-12 09:26:39

+0

@ kempoy211正如我在我的帖子中指出的,C++没有可变长度数组。所以你用最好的VLA标记了答案。那就是答案中提供的代码不符合C++标准,并且不能被其他编译器编译。 – 2014-10-12 12:01:35

回答

1

你ptogram是无效的。例如,你正在声明阵列的

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 
+0

非常感谢!你知道什么是最好的网站来了解更多关于C++吗?对不起后续问题。谢谢 ! =) – kempoy211 2014-10-12 09:29:17

+0

@ kempoy211我不使用网站来学习C++。当我有问题时,我只能看到网站。所以我不能建议学习C++的网站。 – 2014-10-12 09:41:33

+0

我可以使用预处理器fstream向数据库发送所有输入的字符串吗?然后,当我想查看我的数据库时,我可以将它们发送回程序吗?我的意思是,显示或查看它。 – kempoy211 2014-10-15 13:37:48

0

您可以在C++中使用std :: reverse从算法库。与你不需要写这些笨重的循环

编辑: -

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

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

不是,'std :: reverse'会改变容器,OP要求反向遍历 – quantdev 2014-10-12 09:12:05

0
#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 
+0

我可以使用预处理器fstream将输入的&已扫描字符串发送到数据库吗? TIA。 – kempoy211 2014-10-15 13:56:58