将数据文件读入2d数组c ++ [英] reading data file into 2d array c++
问题描述
我有一个有2列和许多行的文本文件。每列由空格分隔。我需要读它们到二维数组进一步计算。
我的数据文件看起来像
I have a text file with 2 columns and many rows. each column is separated by spaces. i need to read them to a 2D array for further calculations. my data file looks like
0.5 0.479425539
1 0.841470985
1.5 0.997494987
2 0.909297427
2.5 0.598472144
3 0.141120008
3.5 -0.350783228
4 -0.756802495
4.5 -0.977530118
5 -0.958924275
我的微弱尝试是
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <ctype.h>
using namespace std;
int main () {
char line,element;
std::ifstream myfile ("C:\\Users\\g\\Desktop\\test.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline(myfile,line);
cout << line<<endl;
_getch();
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
问题是我无法正确读取....它读取整行...如果我将分隔符指定为'space',那么它不读取下一行。
The problem is I'm not able to read them correctly.... its either reading the whole line... if I specify the delimiter as 'space' then, its not reading the next row.
错误。和我应该做什么将数据存储到2d阵列进一步计算。
谢谢
Pls point out whats wrong. and what should i do to store the data into 2d array for further calculations. Thank you
推荐答案
您可以将整行读入 std :: string
,然后使用 std :: istringstream
从该行中提取值。
You can read the whole line into a std::string
, then use std::istringstream
to extract the values from the line.
一个完整的工作程序:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream file("C:\\Users\\g\\Desktop\\test.txt");
std::string line;
// Read a line of input from the file
while (std::getline(file, line))
{
// `istringstream` behaves like a normal input stream
// but can be initialized from a string
std::istringstream iss(line);
float value;
// The input operator `>>` returns the stream
// And streams can be used as a boolean value
// A stream is "true" as long as everything is okay
while (iss >> value)
{
std::cout << "Value = " << value << '\t';
}
// Flush the standard output stream and print a newline
std::cout << std::endl;
}
}
给定文件中的内容,前三行输出应为:
Given the contents in the file being as in the question, the first three lines of output should be:
Value = 0.5 Value = 0.479425539
Value = 1 Value = 0.841470985
Value = 1.5 Value = 0.997494987
对于2d阵列, std :: vector
of std :: array
:
#include <vector>
#include <array>
...
std::vector<std::array<float, 2>> array;
...
float value1, value2;
if (iss >> value1 >> value2)
{
std::cout << "Values = " << value1 << ", " << value2;
array.emplace_back(std::array<int, 2>{{value1, value2}});
}
现在第一行的值是 array [0] [0]
和 array [0] [1]
,最后一行的值是 array [array.size ) - 1] [0]
和 array [array.size() - 1] [1]
。
Now the first line values are array[0][0]
and array[0][1]
, and the last lines values are array[array.size() - 1][0]
and array[array.size() - 1][1]
.
这篇关于将数据文件读入2d数组c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!