2015-10-01 3 views
-1

Код меняет массив символов. Например, если я пишу: char str [] = "Reverse"; он вернет «esreveR» в консоли, теперь я хочу знать, если и как я могу заполнить его строкой?Заполнение массива символов строкой от пользователя. Вход

Что я пробовал: char str [] = userInput; (Но это OBV. Не работал ...)

#include <string> 
#include <iostream> 
using std::cout; 
using std::endl; 

void reverse(char* target) //Requirements specify to have this argument 
{ 
cout << "Before :" << target << endl; // Print out the word to be reversed 
if (strlen(target) > 1) // Check incase no word or 1 letter word is placed 
{ 
    char* firstChar = &target[0]; // First Char of char array 
    char* lastChar = &target[strlen(target) - 1]; //Last Char of char array 
    char temp; // Temp char to swap 
    while (firstChar < lastChar) // File the first char position is below the last char position 
    { 
     temp = *firstChar; // Temp gets the firstChar 
     *firstChar = *lastChar; // firstChar now gets lastChar 
     *lastChar = temp; // lastChar now gets temp (firstChar) 
     firstChar++; // Move position of firstChar up one 
     lastChar--; // Move position of lastChar down one and repeat loop 
    } 
} 
cout << "After :" << target << endl; // Print out end result. 
} 




int main() 
{ 
std::string userInput; 
std::cin >> userInput; 
char str[] = userInput; // <- This is the Key Part of my Question. 
reverse(str); 
} 
+0

Собственно, на это дается ответ в нескольких местах. Выезд: http://www.cplusplus.com/forum/general/4422/ – ejsd1989

ответ

3

В своем коде, userInput является std::string, и ваша функция ожидает char *.

Не вдаваясь в том, как изменить, что для лучшего кода, чтобы получить строку как char *:

char *str = new char[userInput.length() + 1]; 
strcpy(str, userInput.c_str()); 

Только не забудьте delete str; в конце концов.