2017-02-27 90 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

相关问题