Это обсуждение помогло мне решить проблему, с которой я боролся в течение нескольких дней. Я огляделся по всему Интернету, пока не нашел ответ от Джима Тхафа 18 мая в 15:17. С этим ответом мне удалось подключиться. Теперь я хочу вернуть и помочь другим с полным примером. Здесь:
import java.sql.*;
public class MyDBConnect {
public static void main(String[] args) throws SQLException {
try {
String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=whatEverYourHostNameIs)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=yourServiceName)))";
String strUserID = "yourUserId";
String strPassword = "yourPassword";
Connection myConnection=DriverManager.getConnection(dbURL,strUserID,strPassword);
Statement sqlStatement = myConnection.createStatement();
String readRecordSQL = "select * from sa_work_order where WORK_ORDER_NO = '1503090' ";
ResultSet myResultSet = sqlStatement.executeQuery(readRecordSQL);
while (myResultSet.next()) {
System.out.println("Record values: " + myResultSet.getString("WORK_ORDER_NO"));
}
myResultSet.close();
myConnection.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Вы можете объединить int в строку, используя приведенный ниже простой трюк, но учтите, что это работает только тогда, когда целое число состоит из одной цифры. В противном случае добавьте целое число за цифрой к этой строке.
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
Есть больше опций, которые можно использовать для объединения целого числа (или другого числового объекта) со строкой. Это Boost.Format
#include <boost/format.hpp>
#include <string>
int main()
{
using boost::format;
int age = 22;
std::string str_age = str(format("age is %1%") % age);
}
и Карма из Boost.Spirit (v2)
#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
using namespace boost::spirit;
int age = 22;
std::string str_age("age is ");
std::back_insert_iterator<std::string> sink(str_age);
karma::generate(sink, int_, age);
return 0;
}
Boost.Spirit Karma претендует на быть одним из самых быстрых вариантов для преобразования целых в строку .
std :: ostringstream - хороший метод, но иногда этот дополнительный трюк может оказаться полезным для преобразования форматирования в однострочный:
#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
static_cast<std::ostringstream&>( \
std::ostringstream().flush() << tokens \
).str() \
/**/
Теперь вы можете форматировать строки следующим образом:
int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}
При использовании MFC можно использовать управляемый С++ CString
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
, также имеет строковое средство форматирования .
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
Тогда Ваше использование выглядело бы примерно так
std::string szName = "John";
int numAge = 23;
szName += to_string<int>(numAge);
cout << szName << endl;
Погугленный [и протестированный: p]
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
Мне кажется, что самый простой ответ должен использовать эти sprintf
функция:
sprintf(outString,"%s%d",name,age);
Это самый простой способ:
string s = name + std::to_string(age);
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
Бесстыдно украденный от http://www.research.att.com/~bs/bs_faq2.html .
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
Если у Вас есть Повышение, можно преобразовать целое число в строку с помощью boost::lexical_cast<std::string>(age)
.
Иначе должен использовать stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
подход трети А должен был бы использовать sprintf
или snprintf
из библиотеки C.
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
Другие плакаты предложили использовать itoa
. Это не стандартная функция, таким образом, Ваш код не будет портативным при использовании его. Существуют компиляторы, которые не поддерживают его.
В алфавитном порядке:
std::string name = "John";
int age = 21;
std::string result;
// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);
// 2. with C++11
result = name + std::to_string(age);
// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);
// 4. with FastFormat.Write
fastformat::write(result, name, age);
// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);
// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();
// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);
// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);
// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);
// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
#include
) #include
(из стандартного C ++)