将文件中的间隔整数读取到C++数组中

Read spaced integers from a file into an array in C++

本文关键字:读取 C++ 整数 数组 文件      更新时间:2023-10-16

我一直在绞尽脑汁试图弄清楚这一点。我正在尝试从文件中读取一行整数,它们看起来像这样:

20 4 19 1 45 32
34 23 5 2 7

所有数字都介于 1 和 100 之间,并用空格分隔。我想将每个整数存储为数组中的一个元素,该数组将被输入合并排序,但我不知道如何从字符串中获取每个整数。任何帮助,不胜感激。谢谢!

您可以将它们读入向量:

std::ifstream dataFile("ints.dat");
std::istream_iterator<int> dataBegin(dataFile);
std::istream_iterator<int> dataEnd;
std::vector<int> data(dataBegin, dataEnd);

首先,你并不真正想要一个数组——你想要一个vector

其次,使用vector和几个istream_iterator,你可以直接从文件将数据读取到数组中,没有中间的字符串(嗯,可能有一个,但如果是这样,它隐藏在库代码中,而不是你写的任何内容)。

// Open the file:
std::ifstream in("yourfile.txt");
// Read the space-separated numbers into the vector:
std::vector<int> { std::istream_iterator<int>(in),
                   std::istream_iterator<int>() };

请注意,这确实假设您希望将文件中的所有数据读取到 int s 的单个向量中。如果(例如)您只想读取第一行数据,而其余部分保持不变(例如,用于通过其他代码读取),则通常最终会将第一行读取为字符串,然后创建该数据的stringstream,并使用上述代码从stringstream读取数据。

有两个步骤。其中一些其他答案假设您想将整个文件读取到单个向量中;我假设您希望每条单独的行都在自己的向量中。这不是完整的代码,但它应该给你正确的想法。

首先,您需要逐行通读文件。对于每一行,使用 std::getline 将其读入 std::string,其中文件本身使用 ifstream 打开。像这样:

ifstream in_file( "myfile.txt" );
string s;
while( in_file.good() )
{
   getline( in_file, s );
   if( !in_file.fail() )
   {
      // See below for processing each line...
   }
}

假设您已经读取了一行,您应该将其加载到 std::stringstream 中,然后从该字符串流中读取整数。

vector< int > result;
stringstream ss( s );
while( ss.good() )
{
   int x;
   ss >> x;
   if( !ss.fail() )
      result.push_back( x );
}

这部分在上面的内部循环中。在此代码块的末尾,result向量将包含存储在 s 中的行中的所有整数。

顺便说一迭代器有一些不错的技巧(请参阅其他答案),可以使这段代码更加简短。但是,我喜欢这种样式 - 以后很容易适应更复杂的行格式,并且更容易添加错误检查。