2017-02-27 81 views
1

我無法從C++中「上載」的文件中的文本行中分離出特定的字符串。C++從文本文件中的行中分離字符串

以下是我想按列解析的行。

2016年12月6日的「政府和大企業之間的亂倫關係在黑暗中繁盛。〜傑克·安德森[4]」 0 3 39藍白PATRICK巴德韋爾

我需要每條信息中不同的變量,起初我正在執行inFile >> var1 >> var2 >> etc;但是當我到達報價單時,這種方法只會引用報價的第一個單詞:「The」,然後停止。

關於如何將「」中的所有內容放入單個字符串中的任何提示?我目前的代碼如下。

#include <iostream> 
#include <string> 
#include <iomanip> 
#include <fstream> 
#include <stdlib.h> 
#include <cstring> 

using namespace std; 

// int main 

int main() 
{ 

    // Declare variables 
    string userFile; 
    string line; 
    string date; 
    char printMethod; 
    string message; 
    int numMedium; 
    int numLarge; 
    int numXL; 
    string shirtColor; 
    string inkColor; 
    string customerName; 
    string customerEmail; 
    string firstLine; 
    string delimiter = "\""; 


    // Prompt user to 'upload' file 

    cout << "Please input the name of your file:\n"; 
    cin >> userFile; 
    fstream inFile; 
    inFile.open(userFile.c_str()); 

    // Check if file open successful -- if so, process 

    if (inFile.is_open()) 
    { 
     getline(inFile, firstLine); // get column headings out of the way 
     cout << firstLine << endl << endl; 

     while(inFile.good()) // while we are not at the end of the file, process 
     { 
      getline(inFile, line); 
      inFile >> date >> printMethod; 

     } 

     inFile.close(); 
    } 

    // If file open failure, output error message, exit with return 0; 

    else 
    { 

     cout << "Error opening file"; 

    } 

    return 0; 

} 
+1

將整個字符串讀入一個變量,然後_then_進行解析。你有沒有用[regex](http://www.cplusplus.com/reference/regex/)進行實驗? – bejado

+0

如何在將所有內容讀入變量後解析?不,我沒有,首先我聽說它(全新的C++學生)。感謝您迴應順便說一句。 –

+0

打開你的C++書到描述'std :: string'的章節。您必須開始閱讀本章,因爲您在代碼中使用了'std :: string's。那麼,同一章也描述了'std :: string'類具有的許多令人驚歎的方法。像find()一樣,在字符串中找到一個字符,在substr()中找到一個字符串。你還需要什麼?使用'find()'查找字符串各個部分的位置,'substr()'提取它們。問題解決了。學習如何閱讀技術文檔是每個C++開發人員必備的技能。 –

回答

0

可以使用regex模塊來解析從字符串引用的文字你讀過它變成一個變量之後。請務必#include <regex>

就你而言,你正將每行讀入一個名爲line的變量。我們可以將變量line傳遞給名爲regex_search的函數,該函數將提取帶引號的文本匹配並將其放入另一個變量中,在此例中爲resres[1]包含我們感興趣的匹配項,因此我們將其分配給名爲quotedText的變量。

string quotedText; 
while(inFile.good()) // while we are not at the end of the file, process 
{ 
    getline(inFile, line); 

    regex exp(".*\"(.*)\"");   // create a regex that will extract quoted text 
    smatch res;      // will hold the search information 
    regex_search(line, res, exp);  // performs the regex search 
    quotedText = res[1];    // we grab the match that we're interested in- the quoted text 
    cout << "match: " << quotedText << "\n"; 
    cout << "line: " << line << "\n"; 
} 

然後您可以隨意使用quotedText做任何事情。

正則表達式語法本身就是一個整體話題。欲瞭解更多信息,請致電see the documentation

相關問題