如何逐字读取文件的第一行,而将其他行作为逐行存储在变量中
How to read first line of file word by word and other lines as line by line store in variables?
文件的内容格式如下
<>之前3个3ABCDABCDABCD…之前我想读取变量k中的第一个数字和另一个变量n中的另一个数字,其余的行我想存储在字符串中,比如seq,这样
k = 3
n = 3
seq = ABCDABCDABCD..
我需要在c++中这样做。我刚开始学习c++。我知道如何逐行逐字地读取文件,但我不知道如何读取这种特定格式的文件。
执行逐行验证时,使用std::istringstream
分隔行,然后执行常规流操作。
例如,给定一个程序将您的输入文件作为唯一参数:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
std::ifstream inp(argv[1]);
// first line
std::string line;
if (std::getline(inp, line))
{
// load into string stream for parsing.
std::istringstream iss(line);
int k, n;
if (iss >> k >> n)
{
// remaining lines dumped into seq
std::string seq;
while (std::getline(inp, line))
seq.append(line);
// TODO: use k, n, and seq here
}
else
{
std::cerr << "Failed to parse k and/or nn";
}
}
else
{
std::cerr << "Failed to read initial line from filen";
}
}
对第一行进行字符串流似乎有些过分,但是如果您的输入格式要求这样做:
k n
data1
data2
etc...
你想检测什么时候发生类似这样的事情:
k
n
data1
...
如果该检测不重要,则可以直接从输入文件流中提取前两个值,忽略剩余行的其余部分,以启动行追加循环。这样的代码看起来像这样:
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
#include <cstdlib>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
std::ifstream inp(argv[1]);
// read two integers
int k, n;
if (inp >> k >> n)
{
// ignore the remainder of the current line to position the first
// line for our seq append-loop
inp.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::string line;
std::string seq;
while (std::getline(inp, line))
seq.append(line);
// TODO: use k, n, and seq here
}
else
{
std::cerr << "Failed to parse k and/or nn";
}
}
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- 打印逐行存储的文本文件
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- C++如何将字符串逐行转换为双精度
- 在 c++ 中逐行阅读字符串,不要以空格停止
- 使用 QT 逐行读取 JSON
- 逐行读取文件,并将数据插入变量和数组中
- 逐行从文本文件中读取 |C++
- 我遇到使用 c++ 逐行读取输入文件的问题
- 无法逐行读取.csv文件
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- C ++ txt 文件成数组逐行字符串和 int 用于纸牌游戏
- 如何将文件逐行读取到矢量中,然后打印矢量
- C++逐行读取文件
- 如何逐行读取文件并分隔行组件?
- C++ 逐行从文件(包含空格)读取数据
- 对包含整数的文本文件进行排序时,必须逐行进行排序
- C++逐行读取文件,有些行的列与其他行不同
- 如何逐字读取文件的第一行,而将其他行作为逐行存储在变量中