我對 c 很陌生,并嘗試了這個專案并讓它作業。基本上它需要一個單詞和一個句子,然后只要在句子中找到所說的單詞,就會將單詞更改為星號。
我面臨的問題是我嘗試更進一步,要求用戶輸入一個單詞并輸入一個句子,然后使用它們作為存盤變數以與以前完全相同的方式運行代碼,但這不起作用并且只輸出句子的第一個單詞。我無法弄清楚它為什么會這樣做。除了 cin,一切都一樣。我只是不了解 cin 如何處理字串?
主要代碼:
#include <iostream>
#include <string>
#include "functions.hpp"
using namespace std;
int main() {
string word = "brocolli";
string sentence = "Roll up that brocolli. I love brocolli!";
bleep(word, sentence);
for (int i = 0; i < sentence.size(); i ) {
cout << sentence[i];
}
cout << "\n";
return 0;
}
頭檔案:
#include <string>
void asterisk(std::string word, std::string &text, int i);
void bleep(std::string word, std::string &text);
函式檔案:
#include <string>
#include "functions.hpp"
using namespace std;
void asterisk(string word, string &text, int i) {
for (int k = 0; k < word.size(); k) {
text[i k] = '*';
}
}
void bleep(string word, string &text) {
for (int i = 0; i < text.size(); i) {
int match = 0;
for (int j = 0; j < word.size(); j) {
if (text[i j] == word[j]) {
match;
}
}
if (match == word.size()) {
asterisk(word, text, i);
}
}
}
調整主代碼以包含 cin:
#include <iostream>
#include <string>
#include "functions.hpp"
using namespace std;
int main() {
string word;
string sentence;
cout << "Word: ";
cin >> word;
cout << "Sentence: ";
cin >> sentence;
bleep(word, sentence);
for (int i = 0; i < sentence.size(); i ) {
cout << sentence[i];
}
cout << "\n";
return 0;
}
uj5u.com熱心網友回復:
cout << "Sentence: ";
cin >> sentence;
operator>>
您在此處使用的函式在第一個空格字符處停止讀取。它不適合在一行文本中閱讀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/465383.html
下一篇:將整數從字串保存到向量