【发布时间】:2012-02-13 07:58:02
【问题描述】:
我正在尝试使变量存储一个书面问题,然后将其写入文件,但是,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;
}
}
【问题讨论】:
-
调用这个函数的代码是什么样的?它没有碰巧包含这样的内容:
cin >> something;是吗? -
在此之前您还阅读过
cin的其他内容吗?您的缓冲区中可能有前一个输入行的结尾,尤其是当您使用>>读取某些内容时。 -
在 VS2010 上编译并执行良好 (
int main() { addquestiontofile(); return 0; }. -
您的示例编译并运行(在添加主函数后)对我来说很好,无论我输入什么,它都会被写入文件。你确定它什么都不写吗?也许您只是在文件中看错了,请尝试使用 hexeditor,或者尝试在输出后添加一些尾行。
-
myfile.is_open()是否返回true?如果打开失败,您将不知道,因为没有打印任何失败消息来报告这一点。
标签: c++ string file-io getline