从文件,特定行中仅读取数字
Reading only numbers from a file, from a specific line
我正在尝试从包含4行的标头的数据文件中读取,并且还有一个我将存储在2D int array
的数字列表例如
标题
标题
标题
标题
int
int
int
int
......
我需要以某种方式跳过包含文本的标头线,仅使用int行并将其存储到上述2D数组中。当我打开文件并通过它搜索时,它根本不存储任何值,因为一开始就使用了文本。我已经尝试了多个if语句和其他事情来解决这个问题,但是已经工作了。
int main()
{
ifstream imageFile;
imageFile.open("myfile");
if (!imageFile.is_open())
{
exit (EXIT_FAILURE);
}
int test2[16][16];
int word;
imageFile >> word;
while (imageFile.good())
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
test2[i][j] = word;
imageFile >> word;
}
}
}
如评论中所述,您需要先阅读标题 - 在这里,我只是将标题存储在trash
变量中,该字符串是每次存储新标头时都会被覆盖的字符串:
std::string trash;
for (int i =0; i < 4; i++)
std::getline(imageFile, trash);
该部分在您检查文件是否正确打开后进行,并将直接遵循您的原始代码,在该代码中您声明2D数组并读取整数。
在评论中也说过,您需要std::getline
,它读取整个标题线,而不是一个单词,这是我答案的第一个版本(imageFile >> trash;
)。
您可以通过REGEX和模式(修改2D数组的代码这只是可以从文件或字符串提取数字)的示例:
std::string ss;
ifstream myReadFile;
myReadFile.open("foo.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
ss.append(output);
ss.append("n");
}
}
myReadFile.close();
std::regex rx(R"((?:^|s)([+-]?[[:digit:]]+(?:.[[:digit:]]+)?)(?=$|s))"); // Declare the regex with a raw string literal
std::smatch m;
std::string str = ss;
while (regex_search(str, m, rx)) {
std::cout << "Number found: " << m[1] << std::endl; // Get Captured Group 1 text
str = m.suffix().str(); // Proceed to the next match
}
输出:
Number found: 612
Number found: 551
Number found: 14124
相关文章:
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 如何从文件中读取数字并在数组中使用它们?
- 使用模板化函数从CSV文件中读取数字
- 根据数字在 c++ 中作为矩阵的位置从文件中读取数字
- 如何从文件中读取数字序列?
- 如何允许我的程序成功读取数字包含的文件
- 如何仅从C 中的文本文件中读取数字
- 从没有分隔符 C++ 的文件读取数字出现次数
- 读取数字并转换为单词
- 从文件,特定行中仅读取数字
- 从TextFile中读取数字,并检查它们是否在范围内
- C 从文本文件中读取数字,忽略注释
- 从文件读取数字列表到动态数组
- 我正在尝试从文件中读取数字
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- C++如何从文件中读取数字并将其分配到数组中的相应位置
- 读取数字的文本文件,并存储在C++的整数数组中
- 从文件中读取数字
- 从文本中读取数字并输出平均值