程序不会在输入文件中继续读取它
The program doesn't proceed inside the input file to read it
这些是我的代码部分:
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";
}
}
}
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 循环后如何继续阅读
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 失败后可以继续从流读取吗?
- 如何从文件中读取,然后继续从cin读取?
- 控制台将继续关闭,而不是读取 if 语句中的字符串
- 如何只要用户愿意就继续读取输入
- 如何使用 ifstream 打开文件并继续读取直到最后
- C++流继续读取相同的前 5 行
- 如何从文件中读取,直到读取到一个字符,然后跳过一些字符,再次继续读取
- C++在eof()之后继续读取文件
- 分部分读取文件,在最后读取的部分之后继续
- 结束函数,同时从该点继续读取文件
- 程序不会在输入文件中继续读取它
- 从 arduino 读取到 c++ 程序时继续接收 NULL