在处理c-string时,如何用当前输入替换用户第一个输入

时间:2017-01-31 03:57:02

标签: c++ 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?

2 个答案:

答案 0 :(得分:1)

我希望你的目的不需要两个数组声明。而不是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');

}

如果您查看其他内容,请定义它。

答案 1 :(得分:1)

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

struct MapParameters {
    static let midiChannel                     = 0
    static let sizeOfRepeatingMapPattern       = 1
    static let firstMIDIKey                    = 2
    static let lastMIDIKey                     = 3
    static let middleKey                       = 4
    static let referenceMIDIKey                = 5
    static let referenceFrequency              = 6
    static let keysPerFormalOctave             = 7
}

let sourceArray = ["5", "12", "0", "127", "60", "69", "440.0", "12"]

let parameterValue  = sourceArray[MapParameters.referenceFrequency]

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