ifstream在文件中获取错误的字符串
ifstream get the wrong string inside a file
代码如下:
代码:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int id;
char name[50];
ifstream myfile("savingaccount.txt"); //open the file
myfile >> id;
myfile.getline(name , 255 , 'n'); //read name **second line of the file
cout << id ;
cout << "n" << name << endl; //Error part : only print out partial name
return 0;
}
文件内容:
1800567
何瑞章
21
女性
马来西亚语
012-4998192
20,罗荣13,Taman Patani Janam
马六甲
Sungai Dulong
问题:
1.)我希望getline将名称读取到char数组名称中,然后我可以打印出名称,问题是我没有得到全名,我只得到了名称的一部分,为什么会发生这种情况?
谢谢!
问题是myfile >> id
不使用第一行末尾的换行符(n
)。因此,当您调用getline
时,它将从ID的末尾一直读取到该行的末尾,并且您将获得一个空字符串。如果您再次调用getline
,它实际上会返回名称。
std::string name; // By using std::getline() you can use std::string
// instead of a char array
myfile >> id;
std::getline(myfile, name); // this one will be empty
std::getline(myfile, name); // this one will contain the name
我的建议是,所有行都只使用std::getline
,如果一行包含一个数字,则可以使用std::stoi
(如果编译器支持C++11)或boost::lexical_cast
进行转换。
相关文章:
- 将 GetLastError() 转换为带有错误字符串的异常
- Rapidjson 解析错误:字符串 (207) 中的编码无效
- 尝试对字符串[数组]>>cin 并出现错误(" "字符串下标超出范围")
- 如何检索 DirectX 9 的错误字符串
- 从 C++ => C 包装的 API(多线程)传输错误字符串
- 错误字符串下标超出c++范围
- 获取Openssl证书错误中的错误字符串
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 语法错误字符串方法C++
- 取字节字符串的模数
- 对于静态错误字符串,哪个的内存/性能效率更高,或者有替代方案
- 使用 strtok() 的错误字符串比较
- C++ 中的运行时错误字符串声明
- 我收到错误:字符串声明上的 C2501
- GCC:为什么一行代码中的错误(字符串和NULL的比较)会导致一长串错误消息
- 错误C2059:语法错误:'字符串'
- 致命错误:字符串:没有这样的文件或目录编译终止
- C++错误:字符串下标超出范围
- 这里面有什么错误?字符串赋值
- gettwindowtextw不抓取宽字符串