C++ 将文本文件中的字符串与行分开

标签 c++ string file fstream substring

我无法将特定字符串与我用 C++“上传”的文件中的一行文本分开。

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

2016/12/6 s “政府与大企业之间的乱伦关系在黑暗中蓬勃发展。~Jack Anderson [4]” 0 3 39 蓝白色 PATRICK BARDWELL

我需要不同变量中的每条信息,起初我正在执行 inFile >> var1 >> var2 >> 等;但是当我读到引号时,这个方法只接受引号的第一个词:“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;

}

最佳答案

您可以使用 regex 模块在将字符串读入变量后解析字符串中的引用文本。务必#include <regex> .

在您的例子中,您将每一行读入一个名为 line 的变量中.我们可以传递变量 line到一个名为 regex_search 的函数这将提取引用的文本匹配并将其放入另一个变量,在本例中为 res . res[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 .

关于C++ 将文本文件中的字符串与行分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42478520/

相关文章:

JavaScript 字符串格式不起作用

javascript - 如何在 Java 脚本中查找和计算字符串中的元音并以数组形式返回它们?

python - 使用 python 打印图案的替代解决方案

java - 如何在 Java 中替换文本文件中特定索引处的字符串

java - 在Android中,什么时候使用Uri,什么时候使用路径,什么时候在路径前添加 `file://`什么时候不添加?

c++ - 在 Visual Studio2010 中使用 tclap-Templatized C++ 命令行解析器库

c++ - 使用派生类构造函数初始化对象

c++ - std::unique_ptr 试图引用已删除的函数

c# - 在 C# 中比较 2 个 FileAttributes 必须始终返回 true

python - 静态链接 Python,但仍支持外部 .pyd 模块