2017-03-10 79 views
-3

我使用getline从标准输入逐行读入输入,但有兴趣查看单独从getline收到的行的每个单词。getline的解析结果

达到此目的的最佳解决方案是什么?我正在考虑将字符串放入stringstream,然后解析,但想知道是否有更有效的解决方案,或者如果这将甚至工作。

任何建议,将不胜感激。

+5

如果你有兴趣阅读每一个字,为什么你会得到线摆在首位?只是简单的cin >>字符串,它会读直到一个空格....不需要解析 –

+0

我需要得到整个行,因为每行包含一组命令,在一起。每条线都需要与该组不同。目标是使用C++实现SQL样式命令 – umalexans

+0

最好的办法是发布一个例子。如果你真的只想读一行并解析它,如果你使用getline,它会把行存储在一个字符串中,从那里你可以使用一些循环来检查每个单词,通过检查空格并做任何你需要的单词。 –

回答

-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; 
} 
+0

获取字符串中的每个单词然后将其存储在char中?没有意义。 –

0

如果你可以使用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