[英]C++ Splitting strings from ifstream and placing them in seperate arrays
我正在用C ++編寫程序,以從文本文件(日期和當天的高/低溫度)中獲取輸入,將日期和溫度分成兩個單獨的數組。 我的工作已經結束; 但是,我似乎無法適當地分割字符串。 我嘗試使用getline()和.get使用其他方法,但是我需要將字符串保留為STRINGS,而不是chars數組。 我已經使用vector和strtock調查並閱讀了類似問題的答案,只有一個問題:我還是很新,而且研究的越多,我就越困惑。
如果要使用該方法解決問題,則只需要指出正確的使用方法即可。 抱歉,我很容易被所有解決C ++問題的不同方法所淹沒(這就是我非常喜歡使用它的原因。))!
文字樣本:
等等
日期需要存儲在一個數組中,而溫度(高和低)都存儲在另一個數組中。
這是我所擁有的(未完成,但仍供參考)
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>>
,該operator>>
可以讀取遇到的第一個空格(制表符,空格或換行符)並將值存儲在正確的操作數內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.