我使用getline
從標準輸入逐行讀入輸入,但有興趣查看單獨從getline
收到的行的每個單詞。getline的解析結果
達到此目的的最佳解決方案是什麼?我正在考慮將字符串放入stringstream
,然後解析,但想知道是否有更有效的解決方案,或者如果這將甚至工作。
任何建議,將不勝感激。
我使用getline
從標準輸入逐行讀入輸入,但有興趣查看單獨從getline
收到的行的每個單詞。getline的解析結果
達到此目的的最佳解決方案是什麼?我正在考慮將字符串放入stringstream
,然後解析,但想知道是否有更有效的解決方案,或者如果這將甚至工作。
任何建議,將不勝感激。
您可以使用'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中?沒有意義。 –
如果你可以使用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
如果你有興趣閱讀每一個字,爲什麼你會得到線擺在首位?只是簡單的cin >>字符串,它會讀直到一個空格....不需要解析 –
我需要得到整個行,因爲每行包含一組命令,在一起。每條線都需要與該組不同。目標是使用C++實現SQL樣式命令 – umalexans
最好的辦法是發佈一個例子。如果你真的只想讀一行並解析它,如果你使用getline,它會把行存儲在一個字符串中,從那裏你可以使用一些循環來檢查每個單詞,通過檢查空格並做任何你需要的單詞。 –