繁体   English   中英

处理c字符串时,如何用当前输入替换用户的第一输入

[英]how do I replace the user first input with current input when dealing with c-string

我在尝试用其他用户输入替换用户输入时遇到问题。

例如,如果用户输入“我爱狗”,然后我们问他们是否要输入其他字符串,然后输入“我吃了很多冰淇淋”。

如何将用户的第一个输入替换为当前的输入?

// 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');
}

我在选择菜单C时遇到问题。如何用newSentence替换userString?

我希望您不需要两个数组声明。 而不是cin.getline(newSentence,SIZE); 使用cin.getline(userString,SIZE); 它将通过覆盖保存新字符串。

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

}

如果您查找其他内容,请对其进行定义。

C中有一个内置函数,称为strcpy,可以用另一个覆盖一个字符串。

strcpy(userString, newSentence);

现在,左侧的字符串将成为newSentence字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM