程序不会在输入文件中继续读取它

时间:2013-05-17 12:37:33

标签: c++ fileinputstream

这些是我所拥有的代码的一部分:

ifstream inFile;
inFile.open("Product1.wrl");
...
if (!inFile.is_open()){
    cout << "Could not open file to read" << endl;
    return 0;
}
else 
    while(!inFile.eof()){
        getline(inFile, line);
        cout << line << endl;  //this statement only to chech the info stored in "line" string
        if (line.find("PointSet"))
            inFile >> Point1;
    }

输出一遍又一遍地向我显示相同的字符串。所以这意味着文件中的光标不会继续,getline读取同一行。

这种奇怪的行为可能是什么问题?

如果这是相关的: 该文件作为.txt文件打开,并包含我需要的确切信息。

好的,我发现了问题: 即使在第一次迭代后,line.find("PointSet")的返回值为:429467295 ...而我的line字符串只包含一个字母“S”。为什么呢?

1 个答案:

答案 0 :(得分:0)

更改

while(!inFile.eof()){
    getline(inFile, line);

while( getline(inFile, line) ) {

我不知道为什么人们常常被eof()感染,但他们确实如此。

getline>>混合是有问题的,因为>>会在流中留下'\n',因此下一个getline将会返回空白。将其更改为使用getline

if (line.find("PointSet"))也不是你想要的。 find会返回string中的位置,如果找不到则会std::string::npos

此外,您可以更改

ifstream inFile;
inFile.open("Product1.wrl");

ifstream inFile ("Product1.wrl");

这是一个显示读取的版本:

class Point 
{
public:
    int i, j;
};

template <typename CharT>
std::basic_istream<CharT>& operator>>
    (std::basic_istream<CharT>& is, Point& p)
{
    is >> p.i >> p.j;
    return is;
}

int main()
{
    Point point1;
    std::string line;
    while(std::getline(std::cin, line))
    {
        std::cout << line << '\n';  //this statement only to chech the info stored in "line" string
        if (line.find("PointSet") != std::string::npos)
        {
            std::string pointString;
            if (std::getline(std::cin, pointString))
            {
                std::istringstream iss(pointString);
                iss >> point1;
                std::cout << "Got point " << point1.i << ", " << point1.j << '\n';
            }
            else
            {
                std::cout << "Uhoh, forget to provide a line with a PointSet!\n";
            }
        }
    }

}
相关问题