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字节()留出空间。我的假设是,这会导致未定义的行为,因此当您打印时,您无法获得正确的输出。例如,在Linux上,我没有得到第一行空白,我实际上得到了:

2013年4月1日至2013年5月1日
2013年5月1日

这对我来说是一个明确的指示,当插入到达假定的空字节时,插入并没有停止。解决方案是允许您的char数组至少包含9个字节。

在这种情况下使用std::string是有益的,因为它完全避免了这个问题(它是一个动态大小字符串的容器)。它的大小将伴随额外的字符(以及空字节)。