[英]Reading space-separated data with spaces data
我正在從文本文件中讀取行,其中的數據以類似以下的空格分隔成列:
UNITED STATES OF AMERICA WASHINGTON 9629047 291289535
CHINA PEKING 9596960 1273111290
我以前使用以下代碼處理過類似的數據:
ifstream readThis("somefile.txt", ios::in);
while (readThis >> country >> capital >> area >> population) {
// some code...
}
當數據沒有空格(例如“美國”)時,此方法效果很好。 現在發生的事情是,一旦遇到空格,數據就會保存到下一個變量(即“ 2UNITED”將進入country
,“ STATES”將進入capital
,依此類推)。 我要做的是感覺很亂,所以我希望它們是處理數據的更好方法。 這是我現在想做的:
std::getline
閱讀整行。 這種方法看起來更像是K&R的練習,並且可能不是C ++的方法。 我應該提到數據全部正確對齊(“列”的寬度都相同)。 我在想必須要有一種方法來正確讀取“對齊的”數據(基本上是cout << setw(20) << "Hello" << ...
任何想法都歡迎。 謝謝!
我建議一個更好的方法是:
1.使用std::getline
閱讀整行。
2.使用std::substr
和字段寬度提取字段。
3.根據需要修剪字段字符串。
4.處理字段。 5.在步驟1重復,直到讀取失敗。
如果我知道一個正則表達式, 這是一個明顯的例子( 住在這里 ):
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
int main() {
std::istringstream i { "UNITED STATES OF AMERICA WASHINGTON, DC 2233232 23232323\nPOPULAR REPUBLIC OF CHINA BEIJING 23232323 23232323\nBRAZIL BRASILIA 232323233 2323323\n" };
boost::regex r { R"(^(.*?)\s\s+(.*?)\s\s+(\d+)\s\s+(\d+))", boost::regex::perl };
std::string line;
while( std::getline(i, line) ) {
boost::smatch m;
if( !boost::regex_match(line, m, r) )
continue;
auto country = m[1].str();
auto capital = m[2].str();
auto area = m[3].str();
auto pop = m[3].str();
std::cout << capital << ", " << country << ";\n";
}
}
注意
#include <regex>
並且只有在使用libc++
,才可以使用std::regex
, std::smatch
, std::regex_match
,但GNU libstdc++
(最高4.8)無法正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.