Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;涉及getline()和循环的问题_C++ - Fatal编程技术网

C++ C++;涉及getline()和循环的问题

C++ C++;涉及getline()和循环的问题,c++,C++,我正在做一项学校作业,现在我正拼命想弄明白为什么我的程序没有按我希望的那样运行 int main(){ string input; char choice; bool getChoice(char); string getInput(); CharConverter newInput; do{ cout << "Please enter a sentence.\n"; getline(cin, i

我正在做一项学校作业,现在我正拼命想弄明白为什么我的程序没有按我希望的那样运行

int main(){
    string input;
    char choice;

    bool getChoice(char);
    string getInput();

    CharConverter newInput; 

    do{
        cout << "Please enter a sentence.\n";
        getline(cin, input);

        cout << newInput.properWords(input) << endl;

        cout << newInput.uppercase(input) << endl;
        cout << "Would you like to do that again?\n";
        cin >> choice;



    } while (getChoice(choice) == true);

    return 0;
}
intmain(){
字符串输入;
字符选择;
bool-getChoice(char);
字符串getInput();
字符转换器输入;
做{

cout这是因为使用
getline
读取输入与逐个字符读取输入不匹配。当您输入
Y
/
N
字符以指示是否要继续时,您还可以按enter键。这会将
\N
放入输入缓冲区,但
不会从那里获取它。当调用
getline
,则
\n
就在那里,因此函数立即返回一个空字符串

要解决此问题,请将
choice
a
std::string
,使用
getline
读取它,并将第一个字符发送到
getChoice
函数,如下所示:

string choice;
...
do {
    ...
    do {
        getline(cin, choice);
    } while (choice.size() == 0);
} while (getChoice(choice[0]));

您使用的是什么输入?如果输入流中有多行,则getline()将在不等待更多输入的情况下抓取下一行。基本上,我尝试的是允许用户输入完整的句子,并将其传递给两个成员函数。我希望用户能够在下一次迭代中键入新句子…等等。我喜欢这个问题,因为字符串与字符输入是一个容易出错的问题很多人第一次开始用C/C++(或其他许多语言)编程时,那太棒了!你让我开心了。