2014-10-12 43 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