如果是在循环中给字符变量赋值,可以这样:
#include <iostream>
int main()
{
using namespace std;
char ch;
cout << "Type, and I shall repeat.\n";
cin.get(ch);
while(ch != '.')
{
if(ch == '\n')
cout << ch;
else
cout << ++ch;
cin.get(ch);
}
cout << "\nPlease excuse the slight confusion.\n";
return 0;
}
这段代码的效果是用户可以一直输入字符,直到输入'.'为止,中间不论输入空格或回车都可以继续。
如果想把上面的字符变量改为字符数组,也用类似简单的代码,该怎么实现?
自己写了下,但觉得有点复杂了,还用了嵌套循环,请教怎么能更简单?
#include <iostream>
const int Asize = 20;
int main()
{
using namespace std;
char line[Asize];
cout << "Type, and I shall repeat.\n";
int count = 0;
while(count == 0)
{
cin.getline(line, Asize);
for(int i = 0; line[i] != '\0'; i++)
{
if(line[i] == '\n')
cout << line[i];
else
{
if(line[i] == '.')
count++;
cout << ++line[i];
}
}
}
cout << "\nPlease excuse the slight confusion.\n";
return 0;
}