C++ 读/写文本文件问题

标签 c++ text fstream getline

我需要在文本文件中写入数字和文本,由于未知原因,写入有效,读取无效,问题是读取文本,如下例所示:

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 仍然为空...

最佳答案

提取运算符不消耗空格,因此 getline 只是读取第一行中剩余的空格。尝试在调用 getline 之前添加:

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

关于C++ 读/写文本文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5665593/

相关文章:

c++ - fstream中多个get()和单个getline()的理论性能差异

c++ - 退出后fstream输出

c++ - 使用加载二进制文件中的 DLL 中的代码

java - 搜索字符串只打印出没有附加字符的搜索

c - 将文本文件读入 C 中的行数组

css - 使用 CSS 从小到大的中心线长度

c++ - fstream 在不存在的文件上进出

c++ - 离散分布返回整数超出范围

c++ - 模板重构

c++ - 缩放进度条值