У меня есть строка с номером на ints, разделенная разделителем пространства. Может ли кто-нибудь помочь мне разбить строку на ints. Я попытался использовать find, а затем substr. Есть ли лучший способ сделать это?splitting int from string
ответ
Используйте stringsteam:
#include <string>
#include <sstream>
int main() {
std::string s = "100 123 42";
std::istringstream is(s);
int n;
while(is >> n) {
// do something with n
}
}
, если есть только два значения как 100 123 каждый раз есть лучший способ сделать это? – brett
@brett Что вы подразумеваете под "better"? – 2010-08-06 07:36:39
Простой и элегантный ... –
Это была обсуждена в рамках Split a string in C++?
Кроме того, вы можете использовать библиотеку повысить раздвоение функцию для достижения расщепления без петли в вашей программе. Например.
boost :: split (epoch_vector, epoch_string, boost :: is_any_of (","));
A версия используя boost. Версия stringstream от Neil намного проще!
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
int main()
{
const std::string str("20 30 40 50");
std::vector<int> numbers;
boost::tokenizer<> tok(str);
std::transform(tok.begin(), tok.end(), std::back_inserter(numbers),
&boost::lexical_cast<int,std::string>);
// print them
std::copy(numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout,"\n"));
}
Вам даже не нужно повышать для этого. Вы можете просто построить экземпляр 'std :: istringstream is (str);' и затем выполнить 'std :: copy (std :: istream_iterator
@reko_t Ницца! Istream_iterator ожидает, что элементы, разделенные пробелами, могут также обрабатывать другие разделители? –
Ожидает, что элементы, разделенные пробелами, не могут обрабатывать другие разделители. –
У меня были проблемы при чтении и преобразовании более одной строки (я обнаружил, что мне нужно очистить струнный поток). Вот тест, который я сделал с несколькими преобразованиями int/string с чтением/записью в файл ввода/вывода.
#include <iostream>
#include <fstream> // for the file i/o
#include <string> // for the string class work
#include <sstream> // for the string stream class work
using namespace std;
int main(int argc, char *argv[])
{
// Aux variables:
int aData[3];
string sData;
stringstream ss;
// Creation of the i/o file:
// ...
// Check for file open correctly:
// ...
// Write initial data on file:
for (unsigned i=0; i<6; ++i)
{
aData[0] = 1*i;
aData[1] = 2*i;
aData[2] = 3*i;
ss.str(""); // Empty the string stream
ss.clear();
ss << aData[0] << ' ' << aData[1] << ' ' << aData[2];
sData = ss.str(); // number-to-string conversion done
my_file << sData << endl;
}
// Simultaneous read and write:
for (unsigned i=0; i<6; ++i)
{
// Read string line from the file:
my_file.seekg(0, ios::beg);
getline (my_file, sData); // reads from start of file
// Convert data:
ss.str(""); // Empty the string stream
ss.clear();
ss << sData;
for (unsigned j = 0; j<3; ++j)
if (ss >> aData[j]) // string-to-num conversion done
;
// Write data to file:
my_file.seekp(0, ios::end);
my_file << 100+aData[0] << ' '; // appends at the end of stream.
my_file << 100+aData[1] << ' ';
my_file << 100+aData[2] << endl;
}
// R/W complete.
// End work on file:
my_file.close();
cout << "Bye, world! \n";
return 0;
}
- 1. int [] from String или int [] from char []
- 2. String splitting python
- 3. Array Randomly Splitting String
- 4. String splitting using ChunksUpto
- 5. Python parse int from string
- 6. JavaScript parse int from string
- 7. remove int, char from string
- 8. Tokenizing или Splitting String
- 9. Scanner Object - Splitting String
- 10. Powershell String Splitting discrepency
- 11. String splitting problem
- 12. Elasticsearch Splitting a String
- 13. splitting string up
- 14. Python String Double Splitting?
- 15. python string splitting
- 16. Bash, splitting string fail
- 17. C splitting string to stringarray
- 18. SQL Server 2012 String splitting
- 19. Powershell: Splitting String в CSV
- 20. C# string splitting elegant solution
- 21. Weird print string output from INT 0x10
- 22. Enum from string, int и т. Д.
- 23. C++ parse int from string pointer
- 24. string (from substr) преобразование в unsigned int
- 25. Проанализируйте карту int -> list from string
- 26. Django Splitting models from models.py file
- 27. C++ string (int) + string (int)
- 28. Как десериализовать [[int, int, int, int, string, string], [...]] от JSON
- 29. String Splitting with multiple delimiters java
- 30. Java Splitting string, включая шаблоны в Array
Я не уверен, какой точный формат вы описываете - просто пространственно разделенные номера? Пример строки поможет. –
Поиск в Google "splitting string C++" дает: http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html – Akusete
EX: 12 12 14 14 – brett