我正在嘗試制作一個程式,在用戶確定的某個點將一個短語插入另一個短語中。但是,當我嘗試為每個引數、兩個短語以及需要插入另一個短語的位置輸入輸入時,我只能為詢問的第一個引數提供輸入,然后其余的代碼是在沒有輸入其他兩個引數的情況下執行,我不確定為什么我的代碼中會發生這種情況。我的代碼附在下面。
#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;
}
非常感謝您的幫助!:)
uj5u.com熱心網友回復:
我猜因為你打算你的第一個輸入是一個陳述句,它會有空格。
標準輸入運算子cin >> mystr將復制到空格或換行符為止getline(cin, mystr)。
PS 您的代碼將根據您的索引列印整個 mystr、一個 mystr 字符和 substrToBeInserted。不確定這是否是您希望代碼執行的操作。字串有很好的插入子操作mystr.insert(position, substr) ,可以在索引位置之前插入。
(抱歉,還不能評論)
uj5u.com熱心網友回復:
如果要讀取包含空格的字串,則不能使用使用 operator 的格式化輸入函式>>,因為此運算子將停止讀取,如果它看到第一個空格。
因此,如果您嘗試讀取“Hello World Hi”,那么它只會讀取“Hello”。“World”一詞將在您的下一個陳述句中讀取,因此“substrToBeInserted”將包含“World”。cin >> 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380856.html
