c++ - 简单的 C++ 代码在文本文件中跳过一行

标签 c++ debugging

这段代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

const char *filename_param="Simion_PA_Config.txt";
int x_min,x_length,y_min,y_length,z_min,z_length;
ifstream file_param;

template <typename T> void GetParameterSkipLine(ifstream &file,T &parameter);

int main(){
    file_param.open(filename_param);
    if(!file_param){
        cout << "Couldn't open parameter file" << endl;
        exit(0);
    }
    GetParameterSkipLine(file_param,x_min);
    GetParameterSkipLine(file_param,x_length);
    GetParameterSkipLine(file_param,y_min);
    GetParameterSkipLine(file_param,y_length);
    GetParameterSkipLine(file_param,z_min);
    GetParameterSkipLine(file_param,z_length);
    cout << x_min << " " << y_min << " " << z_min << endl;
    cout << x_length << " " << y_length << " " << z_length << endl;
}

template <typename T> void GetParameterSkipLine(ifstream &file,T &parameter){
    string s;
    getline(file,s);
    stringstream line(s);
    file >> parameter;
}

读取这个文件:

0                   !x_min //
150
0
40
0
300
5   1.2
10  1.3
15  0
5   15
2   20

输出:

150 40 300
0 0 5

一切都像在我的文本文件中跳过一行一样。如果我添加一条伪造的行,一切正常。我不知道发生了什么。

我试过重新制作文本文件,在不同的编辑器中打开它。我已经剥离了我的代码以隔离问题并编译您在上面看到的内容,问题仍然存在。

请帮忙,如果这继续削弱我的理智,我可能会开始在 O(N^3) 中排序。

最佳答案

你在那里犯了一个错误。您从文件中读取一行 字符串; getline(文件,s);

然后你阅读另一行

file >> parameter;

所以基本上,您将读入 s 的内容丢弃。

关于c++ - 简单的 C++ 代码在文本文件中跳过一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817220/

相关文章:

c - 使用 time(NULL) 在 C 中创建 Delay() 函数时遇到问题

数组中struct中的c++成员函数指针给出编译错误

c++ - 为什么无法从我的光照着色器访问 G-Buffer?

c++ - 使用QtAudioOutput处理大型QByteArray会导致std::bad_alloc

c++ - 什么预定义宏可用于检测带有 clang 的调试版本?

java - 在 Linux 上调整 Java 中的上下文切换频率

excel - 1004 未找到单元格 - 错误处理

线性内存缓冲区的 C++ 接口(interface)

python - Python 将在哪里为我记录错误(从 PHP 转移)

iphone - Xcode 在自动继续断点处停止