我只想警告你不要使用 Sean Genge 撰寫的類似
文章 中的程式碼。我不知道如何正確地寫,因為論壇關閉了,我無法在上面發表評論。
總的來說,可以使用 STL 和 C++ 非常輕鬆地分割字串。你可以在 STL 中找到兩個不同的 'getline' 函式。一個來自 std::iostream,需要 char 緩衝區,並且不太方便;另一個是 std::string 中的公共函式,允許定義終止字元。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <string>
#include <iostream>
#include <sstream>
int main(int argc, char** arv)
{
// initialize input stream with data
std::istringstream ins("this is a text");
// load words to this container
std::string out;
// read the words until some data in the input stream
while (ins.good())
{
getline(ins, out, ' '); // tell getline to stop on ' ' character
if (!out.empty()) // just fast way to remove unnecessary spaces
std::cout << out << std::endl;
}
return 0;
}
|
另一種方法是僅使用 ANSI。稍微危險一點,但會更快。使用 'strtok' 函式。在術語中:單詞就是標記。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
// this function will stop on any of these characters
char const delimiters[] = " \t\n\r";
// initial string to split
char ins[] = "this is a text";
// this pointer will point to the next word after every 'strtok' call
char *tok = strtok(ins, delimiters);
// if returned pointer is NULL, then there is no more words
while (0 != tok)
{
puts(tok); // print the word
tok = strtok(NULL, delimiters); // move to the next one
}
return 0;
}
|
兩個程式都將返回
可以使用類似 sscanf 的函式將字串分割成幾部分,但為此你必須知道專案的型別,有時還需要知道它們的數量。不要發明別人已經完成並且被證明穩定的程式碼。祝你好運