2015-10-20 107 views
2

我有一个for循环,它向后返回用户的输入。他们输入一个字符串,循环反转它。这里是什么样子:C++将For循环的输出分配给变量

string input;       //what user enters 
const char* cInput = input.c_str(); //input converted to const char* 

for(int i = strlen(cInput) - 1; i >= 0; i--) 
    cout << input[i];  //Outputs the string reversed 

而不必cout << input[i]的,我怎么能设置input[i]作为一个新的字符串的值?就像我想要一个名为string inputReversed的字符串并将其设置为input[i]

换句话说,如果input == helloinput[i] == olleh,我想设置inputReversed等于olleh

这是可行的吗?谢谢!

+0

考虑使用['std :: string :: size'](http://www.cplusplus.com/reference/string/string/size/),而不是转换为'const char *'并使用'strlen'。 –

回答

1

如果我明白你在问什么,你想有一个变量来存储反向字符串和输出? 如果是的话你可以做到这一点

string input, InputReversed; 
         //what user enters 
const char* cInput = input.c_str(); //input converted to const char* 

for(int i = strlen(cInput) - 1; i >= 0; i--){ 

    InputReversed += input[i];  

} 
cout << InputReversed; //Outputs the string reversed 
0

去关闭这个线程可以帮助你。 How do I concatenate const/literal strings in C?

看来你想要的是创建一个新的字符串,在循环结束时将包含向后输入。

string input;       //what user enters 
const char* cInput = input.c_str(); //input converted to const char* 
char inputReversed[len(input)]; 

for(int i = strlen(cInput) - 1; i >= 0; i--) 
    output = strcpy(output, input[i]);  //Outputs the string reversed 
2

只需要声明输出字符串和追加到它,无论是与+=append成员函数:

string inputReversed; 

for(int i = input.size() - 1; i >= 0; i--) 
    inputReversed += input[i];   // this 
// inputReversed.append(input[i]); // and this both do the same thing 

注意,你不需要c_strstrlen,你可以简单地使用sizelength成员函数。

您也可以使代码更易读使用std::reverse

string inputReversed = input; 
std::reverse(inputReversed.begin(), inputReversed.end()); 

或者std::reverse_copy,因为你正在做原始字符串的副本反正:

string inputReversed; 
std::reverse_copy(input.begin(), input.end(), std::back_inserter(inputReversed)); 
+0

谢谢,我喜欢这种方法。我没有使用相反的功能,因为我想做一个回文检测器作为初学者练习:) –

2
string inputReversed(input.rbegin(), input.rend()); 
+0

不错,非常聪明! – emlai