gpt4 book ai didi

c++ - 为什么我的 do while 循环中会得到一个额外的字符?

转载 作者:行者123 更新时间:2023-11-30 05:18:48 25 4
gpt4 key购买 nike

在我下面的代码中,我尝试在文件中写入一个字符,直到用户键入“$”。当我编译它时,它应该打印

Enter $ to exit.
: l
: k
: $

但相反它会打印

Enter $ to exit.
: l
: : k
: : $

这是我的代码:

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
char ch;
ofstream out("Test2.txt");
if(!out)
{
cout<<"Hello!! Sorry."<<endl;
}
cout<<"Enter $ to exit."<<endl;
do
{
cout<<": ";
cin.get(ch);
out.put(ch);
} while(ch!='$');
out.close();
return 0;
}

最佳答案

您的代码缺少一个 get 函数,并在编译时命中了一个 get 函数。您可以通过在 do block 的末尾再添加一个 cin 来避免它。

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
char ch;
ofstream out("Test2.txt");
if(!out)
{
cout<<"Hello!! Sorry."<<endl;
}
cout<<"Enter $ to exit."<<endl;
do
{
cout<<": ";
ch=0;
cin.get(ch);
out.put(ch);
cin.get(ch);
} while(ch!='$');
out.close();
return 0;
}

或者使用 >>> 运算符:

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
char ch;
ofstream out("Test2.txt");
if(!out)
{
cout<<"Hello!! Sorry."<<endl;
}
cout<<"Enter $ to exit."<<endl;
do
{
cout<<": ";
ch=0;
cin>>ch;
out.put(ch);
} while(ch!='$');
out.close();
return 0;
}

关于c++ - 为什么我的 do while 循环中会得到一个额外的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com