将文件中的间隔整数读取到C++数组中
Read spaced integers from a file into an array in C++
我一直在绞尽脑汁试图弄清楚这一点。我正在尝试从文件中读取一行整数,它们看起来像这样:
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
中的行中的所有整数。
顺便说一迭代器有一些不错的技巧(请参阅其他答案),可以使这段代码更加简短。但是,我喜欢这种样式 - 以后很容易适应更复杂的行格式,并且更容易添加错误检查。
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 一种在C++中读取TXT配置文件的简单方法