【问题标题】:Why is my code not allowing me to input values into a string variable with other user inputs for other variables? C++为什么我的代码不允许我将值输入到字符串变量中,而其他用户输入其他变量? C++
【发布时间】:2022-01-18 01:58:49
【问题描述】:

我正在尝试制作一个程序,在用户确定的点将一个短语插入另一个短语。但是,当我尝试为每个参数、两个短语以及需要插入另一个短语的位置获取输入时,我只能为所询问的第一个参数提供输入,然后剩下的代码是在没有输入其他两个参数的情况下执行,我不确定为什么会在我的代码中发生这种情况。我的代码附在下面。

#include <iostream>
#include <string>
#include <cstring>

using namespace std;


int main() {
    string mystr; // original statement
    string substrToBeInserted; // statement to be put into the original statement
    int positionToInsertAfter; //interger value in the string array for where the other statement needs to be put

    cout << endl << "Please enter your statement" << endl;
    cin >> mystr; 
    cout << endl << "Please enter your statement to be inserted" << endl;
    cin >> substrToBeInserted;
    cout << endl << "Please enter where your statement is going to be inserted" << endl;
    cin >> positionToInsertAfter;

    mystr = mystr + mystr[positionToInsertAfter] + substrToBeInserted;
    cout << mystr;

    return 0;
}

非常感谢您的帮助! :)

【问题讨论】:

  • 输入的短语中是否有空格? std::cin &gt;&gt; mystr; 会将输入复制到第一个空格。所以输入singleword 会如你所愿,但输入single word 会将single 放入mystr 并将word 放入substrToBeInserted。

标签: c++ string c-strings cin


【解决方案1】:

我猜因为您打算将第一个输入作为语句,所以它会有空格。

标准输入运算符cin &gt;&gt; mystr 将复制到空格或换行符 请改用getline(cin, mystr)。

附:您的代码将根据您的索引打印整个 mystr、mystr 的一个字符以及 substrToBeInserted。不确定这是否是您希望代码执行的操作。 字符串有很好的插入子操作mystr.insert(position, substr) 在索引位置之前插入。

(抱歉,还不能评论)

【讨论】:

  • 完全次要的一点:换行是空格。它之所以特殊只是因为终端将其视为特殊的,并将输入的字符放入缓冲区,直到它看到换行符。 +1。
【解决方案2】:

如果要读取包含空格的字符串,则不能使用运算符&gt;&gt; 使用格式化输入函数,因为如果该运算符看到第一个空格,它将停止读取。

因此,如果您尝试阅读“Hello World Hi”,那么它将只阅读“Hello”。 “World”一词将在您的下一个语句中读取,因此“substrToBeInserted”将包含“World”。 cin &gt;&gt; positionToInsertAfter;将完全失败,因为它试图将“Hi”转换为整数。

解决方法:需要使用getline函数来读取整行文本,包括空格。

然后,string 类型提供了一个函数插入,您可以简单地使用它。

许多可能的解决方案之一是:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;


int main() {
    string mystr; // original statement
    string substrToBeInserted; // statement to be put into the original statement
    unsigned int positionToInsertAfter; //interger value in the string array for where the other statement needs to be put

    cout << endl << "Please enter your statement" << endl;
    getline(cin, mystr);
    cout << endl << "Please enter your statement to be inserted" << endl;
    getline(cin,substrToBeInserted);
    cout << endl << "Please enter where your statement is going to be inserted" << endl;
    cin >> positionToInsertAfter;

    if (positionToInsertAfter >= mystr.length())
        positionToInsertAfter = mystr.length();
    mystr.insert(positionToInsertAfter, substrToBeInserted);
    cout << mystr;

    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2017-08-30
    • 2019-01-03
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多