【问题标题】:how do I replace the user first input with current input when dealing with c-string处理c字符串时如何用当前输入替换用户的第一个输入
【发布时间】:2017-01-31 03:57:01
【问题描述】:

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

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

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

// 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 ​​的问题。如何将 userString 替换为 newSentence?

【问题讨论】:

  • 如果您的代码是用 C++ 编写的,则无需 c 标签。
  • 什么意思?
  • 只需从标签列表中删除c标签c++cstring从您的问题中。
  • 怎么样:strcpy(userString, newSentence);?无论如何,为什么在使用 C++ 时使用 C 风格的字符串而不是 std::string
  • 您可以使用 cin.getline(newSentence, SIZE); 而不是 cin.getline(userString, SIZE); 。所以不需要更换。只是覆盖。

标签: c++ c string


【解决方案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');

}

如果您在寻找其他东西,请定义它。

【讨论】:

    【解决方案2】:

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

    strcpy(userString, newSentence);
    

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

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 2021-08-25
      • 2020-09-22
      相关资源
      最近更新 更多