getline 不会从变量中读取字符串。 (C++)
我试图让变量存储一个书面问题,然后将其写入文件,但是,getline 不会读取该字符串,当我尝试将其写入文件时,它只是不写入任何内容。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void addquestiontofile(){
ofstream myfile;
// Open file to be written to.
myfile.open("quesitons.txt",ios::ate | ios::app);
string newquestion;
cout << "insert new question: \n";
getline(cin, newquestion); // This is the problem line
if(myfile.is_open())
{
myfile << newquestion;
}
}
I'm trying to make a variable store a written question which will then be written to a file however, the string is not being read by the getline and when I try to write it to the file it simply writes nothing.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void addquestiontofile(){
ofstream myfile;
// Open file to be written to.
myfile.open("quesitons.txt",ios::ate | ios::app);
string newquestion;
cout << "insert new question: \n";
getline(cin, newquestion); // This is the problem line
if(myfile.is_open())
{
myfile << newquestion;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从评论来看,听起来您已经使用了
cin >>>变量
从上一行输入中读取。这会将上一行的末尾留在输入流的缓冲区中,因此下一次调用getline()
将产生一个空字符串。您可以使用以下命令清除该行的其余部分
From the comments, it sounds like you have used
cin >> variable
to read from a previous line of input. This will leave the end of that previous line in the input stream's buffer, so the next call togetline()
will yield an empty string.You can clear the remainder of the line with
之前的输入可能有一个尾随换行符。试试这个:
There is probably a trailing newline from a previous input. Try this: