如何逐字读取文件的第一行,而将其他行作为逐行存储在变量中

How to read first line of file word by word and other lines as line by line store in variables?

本文关键字:其他 逐行 变量 存储 一行 文件 读取 何逐字      更新时间:2023-10-16

文件的内容格式如下

<>之前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";
    }
}