【问题标题】:Parsing result from getline从 getline 解析结果
【发布时间】:2017-03-10 02:46:18
【问题描述】:

我正在使用getline 逐行读取标准输入的输入,但我有兴趣分别查看我从getline 收到的行中的每个单词。

实现这一目标的最佳解决方案是什么?我正在考虑将字符串放入stringstream,然后对其进行解析,但想知道是否有更有效的解决方案,或者这是否可行。

任何建议将不胜感激。

【问题讨论】:

  • 如果你有兴趣阅读每个单词,为什么你会首先得到line?只是简单的 cin >> 字符串,它会一直读到一个空格......不需要解析
  • 我需要获取整行,因为每一行都包含一组一起执行的命令。每条线都需要与集合区分开来。目标是使用 C++ 实现 SQL 风格的命令
  • 最好的方法是发布一个例子。如果您真的只想读取一行并解析它,如果您使用 getline 它将将该行存储在一个字符串中,从那里您可以使用一些循环通过检查空格来读取每个单词,并对单词执行任何您需要的操作。

标签: c++ c++14


【解决方案1】:

如果您可以使用 boost 库,那么这里的一些字符串算法可能有助于将行标记为单词。

#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>

std::vector<std::string> split(std::string value,
                               const std::string& delims) {
    std::vector<std::string> parts;
    boost::trim_if(value, boost::is_any_of(delims));
    boost::split(parts, value,
                 boost::is_any_of(delims), boost::token_compress_on);
    return parts;
}

int main(int, char**) {
    for (size_t lines = 1; !std::cin.eof(); ++lines) {
        std::string input_line;
        std::getline(std::cin, input_line);
        std::vector<std::string> words = split(input_line, " ");
        for (const std::string& word : words) {
            std::cout << "LINE " << lines << ": " << word << std::endl;
        }
    }
}

样本输出:

$ printf "test  foo   bar\n a b c \na b c" | ./a.out 
LINE 1: test
LINE 1: foo
LINE 1: bar
LINE 2: a
LINE 2: b
LINE 2: c
LINE 3: a
LINE 3: b
LINE 3: c

【讨论】:

    【解决方案2】:

    您可以使用 'string.c_str()[index]' 来获取字符串中的每个单词。

    #include <iostream>
    using namespace std;
    int main(void)
    {
        string sIn;
    
        // input 
        getline(cin,sIn);
    
        for (int i=0 ; i<sIn.length() ; i++ ) {
            // get one char from sIn each time
            char c = sIn.c_str()[i];
    
            // insert something you want to do 
            // ...
    
            cout << c << endl;
        }
        return 0;
    }
    

    【讨论】:

    • 获取字符串中的每个单词,然后将其存储在 char 中?没有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多