C++ 如何输入字符串和一组数字?

C++ 如何输入字符串和一组数字?,c++,c++11,C++,C++11,您好,我对如何从文件中输入此块感到困惑 测试线10 20 30 50 60 70 无名氏40 50 60 70 60 50 30 60 90 亨利·史密斯60 70 80 90 100 90 罗伯特·佩恩7080907060809090 山姆休斯顿707090807060 如何收集行的前两个字符串,然后继续收集最多10个整数。它应该能够读取五行中的每一行并正确地收集输入。您可以这样做: #include <array> #include <fstream> #includ

您好,我对如何从文件中输入此块感到困惑

测试线10 20 30 50 60 70

无名氏40 50 60 70 60 50 30 60 90

亨利·史密斯60 70 80 90 100 90

罗伯特·佩恩7080907060809090

山姆休斯顿707090807060


如何收集行的前两个字符串,然后继续收集最多10个整数。它应该能够读取五行中的每一行并正确地收集输入。

您可以这样做:

#include <array>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>



// A structure to hold the input data from the file.
// It has an array of two strings for the names, and
// a vector to hold the numbers (since we don't know
// how many numbers we will get on each line)
struct InputLine
{
    std::array<std::string, 2> names;
    std::vector<int> numbers;
};



int main()
{
    std::ifstream input_file("your_file.txt");
    std::string line;
    // This array will hold the 5 InputLine objects that you read in.
    std::array<InputLine, 5> inputs;
    for (int i = 0; i < 5; i++)
    {
        std::getline(input_file, line);

        // A stringstream can be used to break up the data
        // line into "tokens" of std::string and int for
        // fast and easy processing.
        std::stringstream ss(line);
        InputLine input_line;

        // The for loop reads in the two names
        for (int j = 0; j < 2; j++)
        {
            ss >> input_line.names[j];
        }

        // The while loop reads in as many numbers as exist in the line
        int num;
        while (ss >> num)
        {
            input_line.numbers.push_back(num);
        }

        inputs[i] = input_line;
    }

    return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
//保存文件中输入数据的结构。
//它有一个包含两个字符串的名称数组,和
//一个用来保存数字的向量(因为我们不知道
//我们将在每条线上获得多少个数字)
结构输入线
{
std::数组名称;
std::向量数;
};
int main()
{
std::ifstream输入_文件(“your_file.txt”);
std::字符串行;
//此数组将保存您读入的5个InputLine对象。
std::阵列输入;
对于(int i=0;i<5;i++)
{
std::getline(输入文件,行);
//stringstream可用于分解数据
//在std::string和int的“tokens”中插入一行
//快速和容易处理。
std::stringstream ss(线路);
输入线输入线;
//for循环读取这两个名称
对于(int j=0;j<2;j++)
{
ss>>输入行名称[j];
}
//while循环读取的数字与行中存在的数字一样多
int-num;
while(ss>>num)
{
输入行。数字。推回(num);
}
输入[i]=输入线;
}
返回0;
}

只需在favorite搜索引擎中键入std::cin您就可以在此处查看75个左右的答案: