簡體   English   中英

為什么我的代碼不允許我將值輸入到字符串變量中,而其他用戶輸入其他變量? C++

[英]Why is my code not allowing me to input values into a string variable with other user inputs for other variables? C++

我正在嘗試制作一個程序,在用戶確定的點將一個短語插入另一個短語。 但是,當我嘗試輸入每個參數、兩個短語以及需要插入另一個短語的位置時,我只能為所詢問的第一個參數提供輸入,然后代碼的 rest 是在沒有輸入其他兩個參數的情況下執行,我不確定為什么會在我的代碼中發生這種情況。 我的代碼附在下面。

#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;
}

非常感謝您的幫助::)

我猜因為你打算你的第一個輸入是一個聲明,它會有空格。

標准輸入運算符cin >> mystr將復制到空格或換行符使用getline(cin, mystr)代替。

PS您的代碼將根據您的索引打印整個mystr,mystr的一個字符,以及substrToBeInserted。 不確定這是否是您希望代碼執行的操作。 字符串有很好的插入子操作mystr.insert(position, substr)在索引 position 之前插入。

(對不起,還不能評論)

如果要讀取包含空格的字符串,則不能使用運算符>>使用格式化輸入函數,因為如果該運算符看到第一個空格,它將停止讀取。

因此,如果您嘗試閱讀“Hello World Hi”,那么它將只讀取“Hello”。 “World”一詞將在您的下一個語句中讀取,因此“substrToBeInserted”將包含“World”。 cin >> positionToInsertAfter; 將完全失敗,因為它試圖將“Hi”轉換為 integer 號碼。

解決方案:您需要使用 function getline讀取整行文本,包括空格。

然后, string類型提供了一個 function 插入,您可以簡單地使用它。

許多可能的解決方案之一是:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM