C ++读/写到文本文件的问题 [英] C++ Read/Write to textfile issue

查看:85
本文介绍了C ++读/写到文本文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在文本文件中写数字和文本,原因不明,书写有效,阅读无效,问题在于阅读文本,如下例所示:

I need to write numbers and text in a text file, for an unknown reason, the writing works, the reading does not, the problem is reading the text as in the following example:

fstream ff,ff2;
int a,b;
ff.open("simtestagain.txt",ios::out);
CString mycstring = _T("Name with spaces");
char mycharbuffer[255];         //destination buffer
size_t convertedChars = 0;      //number of characters converted
wcstombs_s( &convertedChars, mycharbuffer, mycstring.GetLength()+1,mycstring.GetBuffer(), _TRUNCATE);
ff << 1 << endl;
ff << mycharbuffer << endl; 
ff << 2 << endl;

ff.close();

ff2.open("simtestagain.txt",ios::in);

ff2 >> a;
ff2.getline(mycharbuffer,255);
mycstring = mycharbuffer;
ff2 >> b;

ff2.close();
AfxMessageBox(mycstring);

a值正常,CString保持为空...

The a value is ok, the CString remains empty...

推荐答案

提取运算符不会占用空白,因此getline只是读取第一行中剩余的空白.尝试在致电getline之前添加此内容:

The extraction operator does not consume the whitespace, so getline is just reading the whitespace that is left over on your first line. Try adding this before your call to getline:

ff2.ignore(255, '\n');

这篇关于C ++读/写到文本文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆