我是C++的初學者,我想知道如何做到這一點。 我想寫一個代碼,其中包含一個文本行。例如。 「你好,stackoverflow是一個非常好的網站」C++打印出限制字數
從輸出我只打印出前三個字,並跳過其餘的。
輸出我想:「你好計算器是」
如果是Java的我會一直使用的字符串分割()。至於C++,我並不知道。他們有什麼相似或C++的方法是什麼?
我是C++的初學者,我想知道如何做到這一點。 我想寫一個代碼,其中包含一個文本行。例如。 「你好,stackoverflow是一個非常好的網站」C++打印出限制字數
從輸出我只打印出前三個字,並跳過其餘的。
輸出我想:「你好計算器是」
如果是Java的我會一直使用的字符串分割()。至於C++,我並不知道。他們有什麼相似或C++的方法是什麼?
運算符>>將流分解爲單詞。
但不檢測行結束。
你可以做的是讀取行然後得到該行的第三個字:
#include <string>
#include <iostream>
#include <sstream>
int main()
{
std::string line;
// Read a line.
// If it succeeds then loop is entered. So this loop will read a file.
while(std::getline(std::cin,line))
{
std::string word1;
std::string word2;
std::string word3;
// Get the first three words from the line.
std::stringstream linestream(line);
linestream >> word1 >> word2 >> word3;
}
// Expanding to show how to use with a normal string:
// In a loop context.
std::string test("Hello stackoverflow is a really good site!");
std::stringstream testStream(test);
for(int loop=0;loop < 3;++loop)
{
std::string word;
testStream >> word;
std::cout << "Got(" << word << ")\n";
}
}
給你一些指點作進一步調查:
對於一個真正的C++解決方案,您可能要查找stream
和streaming operators
像>>
。 CPP Reference是一個很好的在線API參考。
仍然有效的C++,但根源於它的C歷史將是strtok()
函數標記字符串,它有幾個潛在的問題。正如馬丁正確指出的那樣,它修改了源數據,這並不總是可行的。此外,還存在線程安全和/或重入問題。
所以通常你會更好,使用流和C++字符串。
流迭代器對於這種情況是一種矯枉過正。不幸的是,strtok()修改了底層數據,這不是一件好事。 –
嘿,謝謝,你當然是對的。其實我不知道,爲什麼我寫了'迭代器'...我確信我在考慮運算符:-) – Steffen
這是容易的,100%可靠的
void Split(std::string script)
{
std::string singelcommand;
std::stringstream foostream(script);
while(std::getline(foostream,singelcommand))
show_remote_processes(_ssh_session,singelcommand);
}
你可能想看看這個[http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c],這[http://stackoverflow.com/questions/236129/c-how-to-拆分字符串]和其他[http://stackoverflow.com/questions/275404/splitting-string-c]問題。 – JohnIdol