[英]Reading from TextFile in C++
I am a java/C# developer and i am trying to write a C or C++ code to read data from a text file. 我是一名Java / C#开发人员,并且尝试编写C或C ++代码以从文本文件读取数据。 this is very easily done in java and c# but not in c or c++.
在Java和C#中很容易做到这一点,但在C或C ++中却很难做到。
the textfile i am reading looks like this: 我正在阅读的文本文件如下所示:
a,b,c,d,e
1,0,1,1,0
0,1,1,0,0
0,0,0,1,1
i need to store the values in 2 arrays. 我需要将值存储在2个数组中。
the 1st one is a 1D char array which will contain: abcde
第一个是一维char数组,它将包含:
abcde
the 2nd one is a 2D bool array which will contain: 第二个是二维布尔数组,其中包含:
1 0 1 1 0
0 1 1 0 0
0 0 0 1 1
how can i do this? 我怎样才能做到这一点?
I suggest you at least make an attempt at what you are trying to do, to help you get started, here is a basic read out of the example data you provided. 我建议您至少尝试尝试做些什么,以帮助您入门,这是您提供的示例数据的基本读取。 This example should be simple enough to allow you to expand it to meet other data sets.
该示例应该足够简单,以允许您扩展它以满足其他数据集。
#include <iostream>
#include <fstream>
int main() {
const int n_letters = 5;
const int n_columns = 5;
const int n_rows = 3;
char letters[n_letters];
bool booleans[n_rows][n_columns];
std::ifstream stream("myfile.txt");
if (stream) {
for (int i = 0; i < n_letters; ++i) {
stream >> letters[i];
std::cout << letters[i] << ',';
}
std::cout << '\n';
for (int i = 0; i < n_rows; ++i) {
for (int j = 0; j < n_columns; ++j) {
stream >> booleans[i][j];
std::cout << booleans[i][j] << ',';
}
std::cout << '\n';
}
}
return 0;
}
Reads the following text: 读取以下文本:
a b c d e
1 0 1 1 0
0 1 1 0 0
0 0 0 1 1
And outputs: 并输出:
a,b,c,d,e
1,0,1,1,0
0,1,1,0,0
0,0,0,1,1
A first comment: when parsing a file, it's often useful to read the file line by line, and then parse each line, using std::istringstream, or boost::regex, or whatever other technique you please. 第一条评论:解析文件时,逐行读取文件,然后使用std :: istringstream或boost :: regex或您喜欢的任何其他技术来解析每一行通常很有用。 I like boost::regex, because it immediately indicates if there is a syntax error, but carefully designed, istream can as well.
我喜欢boost :: regex,因为它可以立即指示是否存在语法错误,但经过精心设计,istream也可以。
The first thing, in any case, is to specify more precisely the formats: Is there always just one letter? 无论如何,第一件事是更精确地指定格式:是否总是只有一个字母? Are the numbers always Just 0 and 1?
数字是否总是只有0和1? Are there always exactly five values per line?
每行总有五个值吗? Until we know that, it's rather difficult to say more.
在我们不知道这一点之前,很难说更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.