C++ifstream跳过第一行
C++ ifstream skips 1st line
本文关键字:一行 C++ifstream 更新时间:2023-10-16
这是我的代码。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ( ){
ifstream inFile;
char date1[8], date2[8];
int dayTemp1[24], dayTemp2[24];
inFile.open("weatherdata.txt");
if(inFile.fail()){
cout << "File failed to open.";
exit(1);
}
inFile >> date1 >> date2;
cout << date1 << endl;
cout << date2 << endl;
inFile.close();
return 0;
}
weatherdata.txt文件的前两行是:
2013年4月1日
2013年5月1日
date1应该包含第一个日期,但打印时只打印"\n"字符(空行)。我不知道代码是怎么回事,也不知道它为什么跳过第一个日期行。感谢您的任何帮助。我是C++的初学者。
使用std::string代替:
#include <string>
std::string date1;
std::string date2;
//...
inFile >> date1 >> date2;
或
std::getline(inFile, date1);
std::getline(inFile, date2);
@billz为您提供了问题的解决方案,因此我将提供一个解释:
问题是,您的char数组只分配了8个字节(在本例中为字符),但没有为必需的null字节(