当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - how do I replace the user first input with current input when dealing with c-string

问题描述:

I am having issue trying to replace a user input with other user input.

For instance if the user input "I love dog" and then we ask them do they want to input other string and they input "I eat a lot of icecream".

How do I replace the user first input with the current one?

// Function Prototype

int countVowels(char * str);

int countCons(char * str);

int main()

{

const int SIZE = 81; // Max size of the array

//const int V_SIZE = 6; // Size of the vowel array

char newSentence[SIZE];

char userString[SIZE];

//char vowels[V_SIZE] = {'a', 'e', 'i', 'o', 'u'};

char choice; // To hold the menu choice

char *strPtr = userString; // Declare and initialize the pointer

char *sentPtr = newSentence;

// Get the string from the user

cout << "Please enter a string. (Maximum of 80 characters) :\n\n";

cin.getline(userString, SIZE);

do{

// Display the menu and get a choice

cout << "\n\nA. Count the number of vowels in the string \n";

cout << "B. Count the number of consonants in the string \n";

cout << "C. Enter another string \n";

cout << "D. Exit the program \n\n";

cout << "Please make your selection: ";

cin >> choice;

// Menu selections

if (tolower(choice) == 'a')

{

countVowels(userString);

cout << "This string contains " << countVowels(userString);

cout << " vowels. \n";

}

else if (tolower(choice) == 'b')

{

countCons(userString);

cout << "This string contains " << countCons(userString);

cout << " consonants. \n";

}

else if (tolower(choice) == 'c')

{

cout << "Please enter other string: ";

cin.getline(newSentence, SIZE);

userString.replace();

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');

}

else

{

system("PAUSE");

return 0;

}

} while (choice != 'D');

}

I am having the issue with menu selection C. How do I replace userString with newSentence?

网友答案:

I hope no need of two array declaration for your purpose. instead of cin.getline(newSentence, SIZE); use cin.getline(userString, SIZE); it will hold the new string by overwriting.

else if (tolower(choice) == 'c')
{
    cout << "Please enter other string: ";
    cin.getline(userString, SIZE);
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

}

If you looking some thing else, define it.

网友答案:

There is a built in function in C called strcpy to overwrite one string with another.

strcpy(userString, newSentence);

The string on the left will now become the newSentence string.

分享给朋友:
您可能感兴趣的文章:
随机阅读: