get-line 始终获取同一行 C++
get-line gets always the same line C++
我有一个包含这样数据的文件
10000 9.425 1.00216 -0.149976
20000 19.425 0.973893 -0.135456
30000 29.425 1.01707 -0.115423
40000 39.425 1.0181 -0.12074
.
.
.
获取数据我正在做的是读取整行然后用空格分隔行以获得我需要的数据。问题是该文件有 3000 行,所以我试图在 for 循环中获取该行
std::vector<std::string> a;
std::ifstream datas("Data/thermo_stability.dat");
std::string str;
char d=' ';
for(int i=0; i<n; i++)
{
std::getline(datas, str);
tokenize(str,d,a);
x[i]=std::atof((a[1]).c_str());
y[i]=std::atof((a[3]).c_str());
std::cout << x[i] << "\t" << y[i] << std::endl;
}
我注意到出了点问题,所以我添加了那个 cout,发现它总是得到相同的行。我该如何解决这个问题?为什么在调用 getline 后没有得到下一行?当我在循环外执行时,它会转到下一行。
编辑
这是标记化函数
void tokenize(std::string &str, char delim, std::vector<std::string> &out)
{
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos)
{
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
该代码有一些问题:
我没看到 n
设置在哪里,所以你怎么知道它是正确的。读取一行的正确方法是调用 getline()
然后测试它是否有效(可以在一行中完成)。
while(std::getline(datas, str)) {
// Successfully read a line from the file
}
您不需要手动将字符串转换为整数或浮点数。流库会自动执行此操作。
std::istringstream lineStream(std::move(str));
str.clear();
int value1; // please use better names:
double value2;
double value3;
double value4;
lineStream >> value1 >> value2 >> value3 >> value4;
我有一个包含这样数据的文件
10000 9.425 1.00216 -0.149976
20000 19.425 0.973893 -0.135456
30000 29.425 1.01707 -0.115423
40000 39.425 1.0181 -0.12074
.
.
.
获取数据我正在做的是读取整行然后用空格分隔行以获得我需要的数据。问题是该文件有 3000 行,所以我试图在 for 循环中获取该行
std::vector<std::string> a;
std::ifstream datas("Data/thermo_stability.dat");
std::string str;
char d=' ';
for(int i=0; i<n; i++)
{
std::getline(datas, str);
tokenize(str,d,a);
x[i]=std::atof((a[1]).c_str());
y[i]=std::atof((a[3]).c_str());
std::cout << x[i] << "\t" << y[i] << std::endl;
}
我注意到出了点问题,所以我添加了那个 cout,发现它总是得到相同的行。我该如何解决这个问题?为什么在调用 getline 后没有得到下一行?当我在循环外执行时,它会转到下一行。
编辑
这是标记化函数
void tokenize(std::string &str, char delim, std::vector<std::string> &out)
{
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos)
{
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
该代码有一些问题:
我没看到 n
设置在哪里,所以你怎么知道它是正确的。读取一行的正确方法是调用 getline()
然后测试它是否有效(可以在一行中完成)。
while(std::getline(datas, str)) {
// Successfully read a line from the file
}
您不需要手动将字符串转换为整数或浮点数。流库会自动执行此操作。
std::istringstream lineStream(std::move(str));
str.clear();
int value1; // please use better names:
double value2;
double value3;
double value4;
lineStream >> value1 >> value2 >> value3 >> value4;