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

The program doesn't proceed inside the input file to read it

本文关键字:继续 读取 文件 输入 程序      更新时间:2023-10-16

这些是我的代码部分:

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"。为什么?

变化

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";
            }
        }
    }
}