我第一次使用cin.get來將一個字符一次抓到一個字符串「word」中。但由於某種原因,我無法將期限設置爲退出循環命令。不能使用cin.get來斷開循環來檢測句點
#include <cstdio>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctype.h>
#include <string>
using namespace std;
bool isAlpha (char ch);
string replace (string ch);
bool sexist (string ch);
int main()
{
// Exercise 2
string word = "";
string sentence = "";
char next;
cout << "Type your sentence " << endl;
while(next != '.')
{
while(true)
{
cin.get(next);
if(isAlpha(next)) // If alphabet then add the char to word
{
word = word + next;
}
if(isAlpha(next) == false) // If not alphabet then put the char back and stop getting input
{
cin.putback(next);
break;
}
}
if(sexist(word)) // If word is sexist, replace word
{
word = replace(word);
}
sentence = (sentence + " " + word); // Tacking on words to the sentence
word = ""; // Resetting word
}
cout << "Word = " << word << endl;
cout << "Sentence = " << sentence << endl;
return 0;
}
bool isAlpha (char ch)
{
if(isalpha(ch))
{
return true;
}
else return false;
}
bool sexist (string ch)
{
if(ch == "he" || ch == "she")
{
return true;
}
if(ch == "him" || ch == "her")
{
return true;
}
if(ch == "his" || ch == "hers")
{
return true;
}
else
{
return false;
}
}
string replace (string ch)
{
if(ch == "he" || ch == "she")
{
ch = "he or she";
}
if(ch == "him" || ch == "her")
{
ch = "him or her";
}
if(ch == "his" || ch == "hers")
{
ch = "his or her(s)";
}
return ch;
}
解釋我的代碼更多:我試圖在同一時間搶字,通過每次抓住一個字符,並改變是「性別歧視」到「中性」的任何話。抓住這個詞後,如果是性別歧視,我會改變它,否則我不會改變它,然後將它添加到「句子」字符串中。我想要附帶一段時間的最後一個單詞突破外部while循環並進入我的最終輸出行。
但嘗試不同的循環和不同的代碼後,我不能擺脫while循環。是因爲get命令嗎?我對C++非常陌生,所以我可能不瞭解一些基本規則。我曾嘗試在下一次檢測到句點時使用bool將外部while循環設置爲false。我已經嘗試使用goto命令來獲取循環外部的輸出。
無法[複製](http://coliru.stacked-crooked.com/一/ 46c47cc209c18102)。當然,我已經修復了未初始化的「next」。 – LogicStuff
作爲一個側面說明,很容易使用非性別他們/它們/他們不是累贅「他或她。」 –
@SamiKuhmonen是啊肯定是有道理的,這只是我的實驗室提示的一部分。我在一個基本的C++課程。 –