您不应该同时包含"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