字符串_字符串翻转输出

来源:互联网 发布:stm32用ucos还是linux 编辑:程序博客网 时间:2024/04/20 04:54

描述:完成一个字符串的翻转

#include <cstdio>#include <iostream>#include <string>int main(){using namespace std;string str;cin >> str;char temp;//字符串翻转int i, j;for (i= 0,j = str.size() - 1; i < j; ++i, --j){temp = str[i];str[i] = str[j];str[j] = temp;}/*for (int i = 0, int j = str.size() - 1; i < j; ++i, --j){temp = str[i];str[i] = str[j];str[j] = temp;}*/cout << str << endl;return 0;}




意外发现的问题:

C++/C中,  " ,"(逗号运算符)可以完成多个式子赋值操作,但是同时不能完成数据的定义与初始化操作。

如下是错误的操作:

#include <cstdio>#include <iostream>#include <string>int main(){using namespace std;string str;cin >> str;char temp;//字符串翻转/*int i, j;for (i= 0,j = str.size() - 1; i < j; ++i, --j){temp = str[i];str[i] = str[j];str[j] = temp;}*/for (int i = 0, int j = str.size() - 1; i < j; ++i, --j){temp = str[i];str[i] = str[j];str[j] = temp;}cout << str << endl;return 0;}
错误原因:


现在找到错误原因了,应该是:只能对一种数据进行声明与初始化。

//博文链接:http://blog.csdn.net/u010003835/article/details/47393233

改正代码如下:

#include <cstdio>#include <iostream>#include <string>int main(){using namespace std;string str;cin >> str;char temp;//字符串翻转/*int i, j;for (i= 0,j = str.size() - 1; i < j; ++i, --j){temp = str[i];str[i] = str[j];str[j] = temp;}*/for (int i = 0, j = str.size() - 1; i < j; ++i, --j){temp = str[i];str[i] = str[j];str[j] = temp;}cout << str << endl;return 0;}



0 0