C++从ifstream中分离字符串,并将它们放在单独的数组中
C++ Splitting strings from ifstream and placing them in seperate arrays
我正在用C++编写一个程序,从文本文件中获取输入(日期和当天的高/低温度),将日期和温度拆分为两个单独的数组。我已经完成了流程;然而,我似乎无法恰当地划分关系。我尝试过使用getline()和.get的不同方法,但我需要将字符串保持为字符串,而不是字符数组。我已经使用向量和strtock研究并阅读了类似问题的答案,只有一个问题:我还是个新手,研究得越多,我就越困惑。
如果我要用这种方法来解决我的问题,我只需要指出如何应用它的正确方向。为我的愚蠢道歉,用C++解决一个问题很容易被各种不同的方法淹没(这就是我非常喜欢使用它的原因。;)!
文本示例:
- 2007年12月10日56 87
- 2007年10月13日66 77
- 2007年10月14日65 69
等等。
日期需要存储在一个数组中,温度(高和低)需要存储在另一个数组。
以下是我的(未完成,但仅供参考)
int main()
//Open file to be read
ifstream textTemperatures;
textTemperatures.open("temps1.txt");
//Initialize arrays.
const int DAYS_ARRAY_SIZE = 32,
TEMPS_ARRAY_SIZE = 65;
string daysArray[DAYS_ARRAY_SIZE];
int tempsArray[TEMPS_ARRAY_SIZE];
int count = 0;
while(count < DAYS_ARRAY_SIZE && !textTemperatures.eof())
{
getline(textTemperatures, daysArray[count]);
cout << daysArray[count] << endl;
count++;
}
谢谢大家。
尝试以下
#include <iostream>
#include <fstream>
#include <sstream>
//...
std::ifstream textTemperatures( "temps1.txt" );
const int DAYS_ARRAY_SIZE = 32;
std::string daysArray[DAYS_ARRAY_SIZE] = {};
int tempsArray[2 * DAYS_ARRAY_SIZE] = {};
int count = 0;
std::string line;
while ( count < DAYS_ARRAY_SIZE && std::getline( textTemperatures, line ) )
{
std::istringstream is( line );
is >> daysArray[count];
is >> tempsArray[2 * count];
is >> tempsArray[2 * count + 1];
}
这里有一个读取格式化输入的简单程序。您可以很容易地将std::cin替换为std::ifstream,并对循环中的数据执行任意操作。
#include <iostream>
#include <string>
#include <vector>
int main ()
{
std::vector<std::string> dates;
std::vector<int> temperatures;
std::string date;
int low, high;
while ((std::cin >> date >> low >> high))
{
dates.push_back(date);
temperatures.push_back(low);
temperatures.push_back(high);
}
}
这里的魔术是由std::cin
的operator>>
完成的,它读取到遇到的第一个空白(制表、空格或换行),并将值存储在右侧操作数中。
相关文章:
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 从 2 个单独的数组中删除重复元素
- 传递动态数组以接收单独函数中的输入
- 为什么具有单独字符的字符数组不像字符串文字那样以 null 终止符结尾?
- 需要根据读取的数据类型将ifstream提取到单独的数组中
- 如何将单独的数组分组在一起(类似于按一列对表进行排序)
- 显示数组的问题.一切都放在一个单独的行中,但不放入单独的列中
- 输入坐标分为与文件故障的两个单独的数组
- 数组和单独初始化之间的区别
- 如果我在C++中分配一个带有运算符 new[] 的对象数组,但单独释放它们是否仍然构成内存泄漏
- C++:我想将数据从结构复制/存储到单独的数组中
- PIC MICROs:如何在单独的字符数组中转换浮点值
- C++,同时对单独的数组进行排序
- C++ 将数组拆分为 2 个单独的数组
- 在单独的数据中显示数组数据
- 添加到 int 会更改单独的 char 数组
- 读取整数文件并将每一行存储在一个单独的数组中
- 从文本文件中读取,并将每个值存储在 C++ 中的单独数组中