【发布时间】:2016-02-28 09:22:12
【问题描述】:
我第一次使用 cin.get 一次将一个字符抓取到字符串“word”中。但由于某种原因,我无法将句点设置为退出循环命令。
#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 命令转到循环外的输出。
【问题讨论】:
-
无法reproduce。当然,我已经修复了未初始化的
next。 -
附带说明,使用非性别的他们/他们/他们比使用繁琐的“他或她”更容易。
-
@SamiKuhmonen 是的,这绝对是有道理的,这只是我实验室提示的一部分。我正在学习基础 C++ 课程。