您不應該同時包含"stdio.h"
(或更好的<cstdio>
)和<iostream>
。前者允許使用C標準IO函數,而後者則是C++的標準。選擇一個,例如在你的代碼中,你實際上使用了一些<iostrem>
設施,包括那個。
你面對基本的問題requieres 3個步驟:
- 讀取標準輸入直到一個
'.'
或輸入一個'\n'
。
- 存儲除
'.'
或'\n'
以外的每個字符。
- 以相反的順序將讀取的字符發送到標準輸出。
我認爲第二點是關鍵點。你在哪裏儲存你閱讀的角色?在你的代碼中,你似乎使用了c樣式的null終止字符數組,但是你沒有爲此分配必要的內存。
然後,當您使用cin.get()時,您實際上是將一個字符從輸入流中移除,並且在讀取一個字符之前執行了2次。
我也不認爲使用遞歸進行最後一步是個好主意。也許它在你指定的任務中是強制性的,但像這樣使用遞歸(和典型的因子例子)更好地留在書本中。如果你想使用堆棧來完成任務,這是更好地明確地這樣做,就像這裏:
#include <iostream>
#include <stack>
int main() {
char c;
std::stack<char> sc;
while (std::cin.get(c) && c!='\n' && c!='.')
sc.push(c);
std::cout << std::endl;
while (!sc.empty()) {
std::cout << sc.top();
sc.pop();
}
std::cout << std::endl;
return 0;
}
完成這個任務的一個更「自然」的方法是將字符存放在爲std :: string並顯示他們以相反的順序:
#include <iostream>
#include <string>
int main()
{
std::string a;
char c;
while (std::cin.get(c) && c != '.' && c != '\n')
a += c;
std::cout << std::endl;
// you can print what you read with: std::cout << a;
for (std::string::reverse_iterator rit = a.rbegin(); rit != a.rend(); ++rit)
std::cout << *rit;
std::cout << std::endl;
return 0;
}
如果您想使用字符數組存儲輸入,你必須預先分配足夠的內存滿足您的需求。
#include <iostream>
#define MAX_CHARS 128
int main()
{
char a[MAX_CHARS + 1]; // enough to store 128 char and the '\0'
char c;
int counter = 0; // better knowing how many char you read
for (counter = 0; counter < MAX_CHARS
&& std::cin.get(c) && c!='.' && c!='\n'; counter++)
a[counter] = c;
a[counter] = '\0';
std::cout << std::endl;
// you can print what you have read with: std::cout << a;
while(counter > 0) {
--counter;
std::cout << a[counter];
}
std::cout << std::endl;
return 0;
}
如果你正在閱讀從端子輸入,你必須輸入一整行後跟換行符在任何情況下,因爲你正在閱讀一個緩衝輸入。如果您需要無緩衝輸入並在按下.
或enter
時停止正確讀取字符,則不存在標準的C++解決方案,這取決於您的環境。對於semplicity的緣故,你可以使用C-的風格(不建議使用)的getch():
#include <cstdio>
#include "conio.h"
#define MAX_CHARS 128
int main()
{
char a[MAX_CHARS + 1]; // enough to store 128 char and the '\0'
char c;
int counter = 0; // better know how many char you read
while (counter < MAX_CHARS && (c=getch())
&& c!='.' && c!='\n' && c!='\r') {
putchar(c);
a[counter] = c;
counter++
}
a[counter] = '\0';
printf("\n");
// you can print what you read with: printf("%s\n",a);
while(counter > 0) {
--counter;
putchar(a[counter]);
}
printf("\n");
return 0;
}
'CIN >>了'是不確定的行爲,除非用戶永遠不會輸入長度大於1個字符的字符串較大。你是否認爲'a'是一個'std :: string'? – paddy
'a'應該聲明爲'char' – Sebx
好吧,它取決於你。只要告訴你,如果你像現在一樣將它聲明爲'char [2]'將會發生什麼。 (cin.peek()!='\ n'&& cin.peek()!='。'){ cin >> a; – paddy