std::streambuf * buf;
std::ofstream of;
if(!condition) {
of.open("file.txt");
buf = of.rdbuf();
} else {
buf = std::cout.rdbuf();
}
std::ostream out(buf);
, Который связывает базовый streambuf или суда или потока выходного файла к. После этого можно записать в, и это закончится в правильном месте назначения. Если Вы просто хотите это, все идущее в std::cout
входит в файл, можно также сделать
std::ofstream file("file.txt");
std::streambuf * old = std::cout.rdbuf(file.rdbuf());
// do here output to std::cout
std::cout.rdbuf(old); // restore
, Этот второй метод имеет недостаток, что это не безопасное исключение. Вы возможно хотите записать класс, который делает это использование RAII:
struct opiped {
opiped(std::streambuf * buf, std::ostream & os)
:os(os), old_buf(os.rdbuf(buf)) { }
~opiped() { os.rdbuf(old_buf); }
std::ostream& os;
std::streambuf * old_buf;
};
int main() {
// or: std::filebuf of;
// of.open("file.txt", std::ios_base::out);
std::ofstream of("file.txt");
{
// or: opiped raii(&of, std::cout);
opiped raii(of.rdbuf(), std::cout);
std::cout << "going into file" << std::endl;
}
std::cout << "going on screen" << std::endl;
}
Теперь, что бы ни случилось, станд.:: суд находится в чистом состоянии.
You can use Regex.Split for this:
string[] tokens = Regex.Split("basketball, baseball, soccer ,tennis", @"\s*,\s*");
The regex \s*,\s*
can be read as: "match zero or more white space characters, followed by a comma followed by zero or more white space characters".
string[] values = delimitedString.Split(',').Select(s => s.Trim()).ToArray();
string s = "ping pong, table tennis, water polo";
string[] myArray = s.Split(',');
for (int i = 0; i < myArray.Length; i++)
myArray[i] = myArray[i].Trim();
That will preserve the spaces in the entries.
Split the items on the comma:
string[] splitInput = yourInput.Split(',', StringSplitOption.RemoveEmptyEntries);
and then use
foreach (string yourString in splitInput)
{
yourString.Trim();
}
You can split on either comma or space, and remove the empty entries (those between a comma and a space):
string[] values = delimitedString.Split(new char[]{',',' '}, StringSplitOption.RemoveEmptyEntries);
Edit:
However, as that doesn't work with values that contain spaces, instead you can split on the possible variations if your values can contain spaces:
string[] values = delimitedString.Split(new string[]{" , ", " ,", ", ", ","}, StringSplitOptions.None);
I would firstly split a text by ",", and then use Trim method to remove spaces on start and end of the each string. This will add support for string with spaces to your code.