C++从ifstream中分离字符串,并将它们放在单独的数组中

C++ Splitting strings from ifstream and placing them in seperate arrays

本文关键字:单独 数组 ifstream 分离 字符串 C++      更新时间:2023-10-16

我正在用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::cinoperator>>完成的,它读取到遇到的第一个空白(制表、空格或换行),并将值存储在右侧操作数中。